码迷,mamicode.com
首页 > Web开发 > 详细

Hibernate之映射集合属性

时间:2015-07-14 22:39:27      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:

这里先将集合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

Hibernate之映射集合属性

标签:

原文地址:http://blog.csdn.net/lindonglian/article/details/46883225

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!