hibernate4 對映集合屬性List
阿新 • • 發佈:2019-02-03
package com.xxx.domain; import java.util.ArrayList; import java.util.List; public class Person { private Integer id; private String name; private Integer age; private List<String> subject = new ArrayList<String>(); public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public List<String> getSubject() { return subject; } public void setSubject(List<String> subject) { this.subject = subject; } }
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping SYSTEM "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" > <hibernate-mapping package="com.xxx.domain"> <class name="Person" table="tb_person"> <id name="id" column="person_id"> <generator class="native"/> </id> <property name="name" column="name" type="string"/> <property name="age" column="age" type="integer"/> <list name="subject" table="tb_subject"> <key column="person_id"/> <list-index column="index_id"/> <element column="value" type="string" /> </list> </class> </hibernate-mapping>
public class PersonTest { private SessionFactory sessionFactory=null; @Before public void setUp() throws Exception { Configuration config=new Configuration().configure(); ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build(); sessionFactory=config.buildSessionFactory(serviceRegistry); } @After public void tearDown() throws Exception { sessionFactory.close(); } @Test public void test() { //this.add(); this.find(); } public void add(){ Session session=sessionFactory.openSession(); Transaction ts= session.beginTransaction(); Person person=new Person(); person.setName("小輝"); person.setAge(22); List<String> subject=person.getSubject(); subject.add("數學"); subject.add("語文"); subject.add("英語"); subject.add("物理"); subject.add("化學"); person.setSubject(subject); session.save(person); ts.commit(); } public void find(){ Session session=sessionFactory.openSession(); Transaction ts= session.beginTransaction(); Person person=(Person)session.load(Person.class, 2); System.out.println("使用者名稱:"+person.getName()); System.out.println("年齡:"+person.getAge()); List<String> subject=person.getSubject(); Iterator item=subject.iterator(); while(item.hasNext()){ String name=(String)item.next(); System.out.println("科目:"+name); } ts.commit(); } }
表結構
person表
subject表