映射集合属性之②:数组属性

来源:互联网 发布:万网域名怎么转出 编辑:程序博客网 时间:2024/05/16 09:09

hibernate.cfg.xml :

<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools.                   --><hibernate-configuration>    <session-factory>        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>        <property name="connection.url">jdbc:mysql://localhost:3306/temp</property>        <property name="connection.username">root</property>        <property name="connection.password">mysqladmin</property>        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>        <property name="hbm2ddl.auto">update</property>        <property name="show_sql">true</property>        <property name="format_sql">true</property>        <mapping resource="db/mapping/Person.hbm.xml"/>    </session-factory></hibernate-configuration>
Person.java :

public class Person {private int id;private String name;private int age;private String[] schools;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String[] getSchools() {return schools;}public void setSchools(String[] schools) {this.schools = schools;}}
Person.hbm.xml :

<?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="db.domain">    <class name="Person" table="persons">            <id name="id">            <generator class="identity"></generator>        </id>                <property name="name" type="string"/>        <property name="age" type="integer"/>                <!-- 映射数组属性 -->        <array name="schools" table="schools">            <key column="person_id" not-null="true"/>            <list-index column="list_order"/>            <element column="school_name" type="string"/>        </array>             </class></hibernate-mapping>
Test.java :

public class Test {public static void main(String[] args) {Session session=HibernateSessionFactory.getSession();Transaction txt=session.beginTransaction();Person p1=new Person();p1.setName("小红");p1.setAge(18);String[] schools1=new String[]{"小学","初中","高中"};p1.setSchools(schools1);Person p2=new Person();p2.setName("小明");p2.setAge(22);String[] schools2=new String[]{"小学","初中","高中","大学"};p2.setSchools(schools2);session.save(p1);session.save(p2);txt.commit();HibernateSessionFactory.closeSession();}}



原创粉丝点击