1.定义实体
public class User { private int userId; private String userName; private Set<String> address; set... get... }
2.写映射文件
<?xml version="1.0" encoding="utf-8" ?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.juaner.hibernate.address"> <class name="User" table="t_user"> <id name="userId" column="u_id"> <generator class="native"/> </id> <property name="userName" column="u_name"/> <set name="address" table="t_address"> <!--外键字段--> <key column="u_id"></key> <!--其他字段,没有bean与其对应,必须制定type--> <element column="address" type="string"></element> </set> <!--list有先后顺序,list-index制定排序列的名称--> <!--<list name="addressList" table="t_addresslist">--> <!--<key column="u_id"></key>--> <!--<list-index column="idx"></list-index>--> <!--<element column="address" type="string"></element>--> <!--</list>--> </class> </hibernate-mapping>
3.保存数据
@Test public void testSave()throws Exception{ Session session = sf.openSession(); session.beginTransaction(); Set<String> address = new HashSet<String>(); address.add("广州"); address.add("北京"); User user = new User(); user.setUserName("jack"); user.setAddress(address); session.save(user); session.getTransaction().commit(); session.close(); }
4.结果
t_user表:
t_address表:
5.获取数据
@Test public void test3()throws Exception{ Session session = sf.openSession(); session.beginTransaction(); User user = (User) session.get(User.class, 1); System.out.println(user); //当查询用户,同时可以获取用户关联的list集合的数据 //当使用到集合数据时,才向数据库发送执行的sql语句(懒加载,可以提高执行效率) System.out.println(user.getAddressList()); session.getTransaction().commit(); session.close(); }