这里先将集合Set在数据库中的存储。就是新建一个表,新建的表的主键对应另一张的外键,而集合的每个值对应一条记录,以同一个set的数据以主键值相同的记录区分。
package test.hibernate.set; import java.util.Set; public class User { private Integer id; private String name; private Set<String> addressSet; 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 Set<String> getAddressSet() { return addressSet; } public void setAddressSet(Set<String> addressSet) { this.addressSet = addressSet; } }
package test.hibernate.set; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.junit.Test; public class App { private static SessionFactory sessionFactory = new Configuration()// .configure()// .addClass(User.class)// 添加Hibernate实体类(加载对应的映射文件) .buildSessionFactory(); @Test public void testSave() throws Exception { Session session = sessionFactory.openSession(); session.beginTransaction(); // -------------------------------------------- // 构建对象 User user = new User(); user.setName("李明"); Set<String> set = new HashSet<String>(); set.add("广东省"); set.add("深圳市"); set.add("福田区"); user.setAddressSet(set); // 保存 session.save(user); // -------------------------------------------- session.getTransaction().commit(); session.close(); } @Test public void testGet() throws Exception { Session session = sessionFactory.openSession(); session.beginTransaction(); // 获取数据 User user = (User) session.get(User.class, 1); // 显示数据 System.out.println(user.getId()); System.out.println(user.getName()); System.out.println(user.getAddressSet()); session.getTransaction().commit(); session.close(); } }
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="test.hibernate.set"> <class name="User" table="t_user"> <id name="id"> <generator class="native"></generator> </id> <property name="name" /> <!-- addressSet属性是Set类型 --> <set name="addressSet" table="user_addressSet"> <key column="userId"></key> <element type="string" column="address"></element> </set> </class> </hibernate-mapping>
注意set的映射
连续加载两次的结果
版权声明:本文为博主原创文章,未经博主允许不得转载。http://blog.csdn.net/lindonglian
时间: 2024-10-22 21:53:34