****************
hibernate.cfg.xml
***************
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.gjt.mm.mysql.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/list</property><!-- ///表示连接本机的数据库//localhost:3306 -->
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="blog/hibernate/domain/Nation.hbm.xml"/>
<mapping resource="blog/hibernate/domain/City.hbm.xml"/>
</session-factory>
</hibernate-configuration>
****************
HibernateUtil.java
***************
package blog.hibernate;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public final class HibernateUtil {
private static SessionFactory sessionFactory;
private HibernateUtil(){}
static{
Configuration cfg = new Configuration();
sessionFactory = cfg.configure("hibernate.cfg.xml").buildSessionFactory();
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
public static Session getSession(){
return sessionFactory.openSession();
}
}
****************
City.java
***************
package blog.hibernate.domain;
public class City {
private int id;
private String name;
private String postcode;
private Nation nation;
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public Nation getNation() {
return nation;
}
public void setNation(Nation nation) {
this.nation = nation;
}
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;
}
}
****************
City.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="blog.hibernate.domain">
<class name="City" table="city">
<id name="id" column="CITY_ID">
<generator class="native"/>
</id>
<property name="name" column="CITY_NAME" type="string" />
<property name="postcode" column="POST_CODE"/>
<many-to-one name="nation" class="Nation" column="NATION_ID" />
</class>
</hibernate-mapping>
****************
Nation.java
***************
package blog.hibernate.domain;
import java.util.ArrayList;
import java.util.List;
public class Nation {
private int id;
private String name;
private List<City> citys = new ArrayList<City>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<City> getCitys() {
return citys;
}
public void setCitys(List<City> citys) {
this.citys = citys;
}
@Override
public String toString() {
return "Nation{" + "id=" + id + ", name=" + name + '}';
}
}
****************
Nation.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="blog.hibernate.domain">
<class name="Nation" table="nation">
<id name="id" column="NATION_ID">
<generator class="native"></generator>
</id>
<property name="name" column="NATION_NAME" not-null="true"></property>
<list name="citys" inverse="false">
<key column="NATION_ID" />
<list-index column="CITYNAME"/>
<one-to-many class="City" />
</list>
</class>
</hibernate-mapping>
****************
一对多junit 测试
***************
package juint.test;
import blog.hibernate.HibernateUtil;
import blog.hibernate.domain.City;
import blog.hibernate.domain.Nation;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* list
* @author Administrator
*/
public class Many2OneAndOne2Many {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@Test
public void test() {
add();
query();
query2();
}
public void add() {
Session session = null;
Transaction tx = null;
try {
City city1 = new City();
city1.setName("中国·唐山");
city1.setPostcode("063009");
City city2 = new City();
city2.setName("中国·天津");
city2.setPostcode("356148");
List< City> citys = new ArrayList< City>();
citys.add(city1);
citys.add(city2);
Nation nation = new Nation();
nation.setName("中国");
nation.setCitys(citys);
// 当Nation.hbm.xml文件中map节点的inverse = "false"或不写时(即默认,false)
// 这行代码的作用是Hibernate可以根据nation中的citys去更新city表中的CITYNAME
// 如果没有setCitys则city表中的CITYNAME为null
// 当Nation.hbm.xml文件中map节点的inverse = "true"时不起作用
city1.setNation(nation);
city2.setNation(nation);
session = HibernateUtil.getSession();
tx = session.beginTransaction();
session.save(nation);
session.save(city1);
session.save(city2);
System.out.println("Save succeed");
tx.commit();
} catch (Exception ex) {
Logger.getLogger(Many2OneAndOne2Many.class.getName()).log(Level.SEVERE, null, ex);
if (tx != null) {
tx.rollback();
}
} finally {
if (session != null) {
session.close();
}
}
}
public void query() {
List<City> citys = null;
Session session = HibernateUtil.getSession();
try {
citys = ((Nation) session.get(Nation.class, 1)).getCitys();
for (Iterator<City> it = citys.iterator(); it.hasNext();) {
City city = it.next();
System.out.println(city.getId() + city.getName() + city.getNation());
}
} catch (HibernateException hibernateException) {
Logger.getLogger(Many2OneAndOne2Many.class.getName()).log(Level.SEVERE, null, hibernateException);
} finally {
if (session != null) {
session.close();
}
}
}
public void query2() {
Session session = HibernateUtil.getSession();
try {
City city = (City) session.get(City.class, 1);
System.out.println(city.getId());
Nation nation = city.getNation();
System.out.println(nation);
} catch (HibernateException hibernateException) {
Logger.getLogger(Many2OneAndOne2Many.class.getName()).log(Level.SEVERE, null, hibernateException);
} finally {
if (session != null) {
session.close();
}
}
}
}
测试结果:
Hibernate: insert into nation (NATION_NAME) values (?)
Hibernate: insert into city (CITY_NAME, POST_CODE, NATION_ID) values (?, ?, ?)
Hibernate: insert into city (CITY_NAME, POST_CODE, NATION_ID) values (?, ?, ?)
Save succeed
Hibernate: update city set NATION_ID=?, CITYNAME=? where CITY_ID=?
Hibernate: update city set NATION_ID=?, CITYNAME=? where CITY_ID=?
Hibernate: select nation0_.NATION_ID as NATION1_0_0_, nation0_.NATION_NAME as NATION2_0_0_ from nation nation0_ where nation0_.NATION_ID=?
Hibernate: select citys0_.NATION_ID as NATION4_1_, citys0_.CITY_ID as CITY1_1_, citys0_.CITYNAME as CITYNAME1_, citys0_.CITY_ID as CITY1_1_0_, citys0_.CITY_NAME as CITY2_1_0_, citys0_.POST_CODE as POST3_1_0_, citys0_.NATION_ID as NATION4_1_0_ from city citys0_ where citys0_.NATION_ID=?
1中国·唐山Nation{id=1, name=中国}
2中国·天津Nation{id=1, name=中国}
Hibernate: select city0_.CITY_ID as CITY1_1_0_, city0_.CITY_NAME as CITY2_1_0_, city0_.POST_CODE as POST3_1_0_, city0_.NATION_ID as NATION4_1_0_ from city city0_ where city0_.CITY_ID=?
1
Hibernate: select nation0_.NATION_ID as NATION1_0_0_, nation0_.NATION_NAME as NATION2_0_0_ from nation nation0_ where nation0_.NATION_ID=?
Nation{id=1, name=中国}