资料:
示例:国家、省份、城市的三级连动。
一、数据库要求:
1、国家表nation:nid国家编号、nname国家名称
2、省份表province:pid省份编号、pname省份名称、nid国家的编号
3、城市表city:cid城市编号、cname城市名称、pid省份编号
二、实体类:
1、国家表Nation.java的实体类(封装继承省略):
1.1、配置式:
/**
* 编号
*/
private String nid;
/**
* 国家名
*/
private String nname;
// 创建set集合:原因:唯一性,作用:用来保存N个省份
Set<Province> sp = new HashSet<>();
1.2、注解式:
@Entity//指定为实体类
@Table(name="nation")//对象数据库的表
public class Nation {
@Id
@GenericGenerator(name="myid",strategy="guid")
@GeneratedValue(generator="myid")//指名主键
private String nid;//国家编号
@Column(name="nname")
private String nname;//国家名称
//设置1VN的关系
@OneToMany(targetEntity=Province.class,cascade=CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name="nid")
private Set<Province> sp=new HashSet<>();//set集合用户存放N个省份对象
public String getNid() {
return nid;
}
public void setNid(String nid) {
this.nid = nid;
}
public String getNname() {
return nname;
}
public void setNname(String nname) {
this.nname = nname;
}
public Set<Province> getSp() {
return sp;
}
public void setSp(Set<Province> sp) {
this.sp = sp;
}
public Nation(String nid, String nname, Set<Province> sp) {
super();
this.nid = nid;
this.nname = nname;
this.sp = sp;
}
public Nation() {
super();
// TODO Auto-generated constructor stub
}
}
2、省份表Province.java的实体类(封装继承省略):
2.1、配置式:
/**
* 编号
*/
private String pid;
/*
* 省份名
*/
private String pname;
// private String nid;
// 创建Nation对象:用来获取国家表的编号
private transient Nation nation;
// 创建set集合:原因:唯一性,作用:用来保存N个城市
private Set<City> sc = new HashSet<>();
2.2、注解式:
@Entity//指名实体类
@Table(name="province")//对应数据库表
public class Province {
@Id
@GenericGenerator(name="myid",strategy="guid")
@GeneratedValue(generator="myid")//指名主键
private String pid;//省份编号
@Column(name="pname")
private String pname;//省份名称
//设置与国家表的NV1关系
@ManyToOne(targetEntity=Nation.class)
@JoinColumn(name="nid",insertable = false)
private Nation nation;//国家表的对象
//设置与城市表的1VN关系
@OneToMany(targetEntity=City.class,cascade=CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name="pid")
private Set<City> sc=new HashSet<>();//用于保存城市表的N个对象
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Nation getNation() {
return nation;
}
public void setNation(Nation nation) {
this.nation = nation;
}
public Set<City> getSc() {
return sc;
}
public void setSc(Set<City> sc) {
this.sc = sc;
}
public Province(String pid, String pname, Nation nation, Set<City> sc) {
super();
this.pid = pid;
this.pname = pname;
this.nation = nation;
this.sc = sc;
}
public Province() {
super();
// TODO Auto-generated constructor stub
}
}
3、城市表City.java的实体类(封装继承省略):
3.1、配置式:
/**
* 编号
*/
private String cid;
/**
* 城市名
*/
private String cname;
// private String pid;
// 创建Province对象:用来获取省份表的编号
private transient Province province;
3.2、注解式:
@Entity//指名为实体类
@Table(name="city")//对应数据库的表
public class City {
@Id
@GenericGenerator(name="myid",strategy="guid")
@GeneratedValue(generator="myid")//指名主键
private String cid;//城市编号
@Column(name="cname")
private String cname;//城市名称
//设置与省份表的NV1关系
@ManyToOne(targetEntity=Province.class)
@JoinColumn(name="pid")
private Province province;//省份表的对象
public String getCid() {
return cid;
}
public void setCid(String cid) {
this.cid = cid;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public Province getProvince() {
return province;
}
public void setProvince(Province province) {
this.province = province;
}
public City() {
super();
// TODO Auto-generated constructor stub
}
public City(String cid, String cname, Province province) {
super();
this.cid = cid;
this.cname = cname;
this.province = province;
}
}
三、配置映射文件:
在src/main/resources路径下创建连接数据库的hibernate.cfg.xml文件,具体如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">sasa</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/chencao?useUnicode=true&characterEncoding=UTF-8</property>
<property name="hibernate.connection.username">root</property>
<!-- 配置式的配置映射 -->
<mapping resource="com/zking/hibernate05/entity/Nation.hbm.xml" />
<mapping resource="com/zking/hibernate05/entity/Province.hbm.xml" />
<mapping resource="com/zking/hibernate05/entity/City.hbm.xml" />
<!--注解式的配置映射-->
<!--<property name="show_sql">true</property>-->
<!--<property name="format_sql">true</property>-->
<!--<mapping class="com.zking.hibernate05_02.entity.Nation" />-->
<!--<mapping class="com.zking.hibernate05_02.entity.Province" />-->
<!--<mapping class="com.zking.hibernate05_02.entity.City" />-->
</session-factory>
</hibernate-configuration>
在src/main/java路径下创建连接数据库的三个实体类的映射文件,具体如下(注解式则省略xxx..hbm.xml文件):
国家表的映射文件(Nation.hbm.xml):
<!--inverse 关联关系交给多端维护(提高性能) lazy 是否关闭懒加载 -->
<set name="sp" table="PROVINCE" inverse="false" lazy="true"
cascade="all-delete-orphan">
<key>
<column name="NID" />
</key>
<one-to-many class="com.zking.hibernate05.entity.Province" />
</set>
省份表的映射文件(Province.hbm.xml):
<!-- 对应国家表 -->
<many-to-one name="nation" class="com.zking.hibernate05.entity.Nation"
fetch="join">
<column name="nid" />
</many-to-one>
<!-- 对应城市表 -->
<set name="sc" table="CITY" inverse="false" lazy="true"
cascade="all-delete-orphan">
<key>
<column name="PID" />
</key>
<one-to-many class="com.zking.hibernate05.entity.City" />
</set>
城市表的映射文件(City.hbm.xml):
<!-- 对应省份表 -->
<many-to-one name="province" class="com.zking.hibernate05.entity.Province" fetch="join">
<column name="pid" />
</many-to-one>
四、测试类中实现CRUD:
/**
*
* @Title: add
* @Description: 新增数据的方法
* @return void
*/
// @Test
public void add() {
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// 国家赋值
Nation n1 = new Nation();
n1.setNname("中国");
// 省份赋值
Province p1 = new Province();
p1.setPname("湖南");
Province p2 = new Province();
p2.setPname("湖北");
// 国家设置省份
n1.getSp().add(p1);
n1.getSp().add(p2);
// 省份设置国家
p1.setNation(n1);
p2.setNation(n1);
// 城市赋值
City c1 = new City();
c1.setCname("益阳");
City c2 = new City();
c2.setCname("长沙");
City c3 = new City();
c3.setCname("武汉");
// 省份设置城市
p1.getSc().add(c1);
p1.getSc().add(c2);
p2.getSc().add(c3);
// 城市设置省份
c1.setProvince(p1);
c2.setProvince(p1);
c3.setProvince(p2);
// 保存
session.save(n1);
transaction.commit();
session.close();
sessionFactory.close();
}
/**
*
* @Title: find
* @Description: 查询的方法
* @return void
*/
// @Test
@Action("find")
public String find() throws Exception {
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// 查询国家
// 查询可能会出现懒加载异常(Session 关闭后再查)
Nation n = session.get(Nation.class, "6de14c82-b4c8-11e8-8972-80fa5b5015f0");
// System.out.println("国家名:" + n.getNname());
//
// // 得到省份
// Set<Province> sp = n.getSp();
// for (Province p : sp) {
// System.out.println("省份名:" + p.getPname());
//
// // 得到城市
// Set<City> sc = p.getSc();
// for (City c : sc) {
// System.out.println("城市名:" + c.getCname());
// }
// }
List<Nation> list = new ArrayList<Nation>();
list.add(n);
String out = JSON.toJSONString(list);
HttpServletResponse response = ServletActionContext.getResponse();
response.getWriter().println(out);
response.getWriter().flush();
response.getWriter().close();
System.out.println(out);
transaction.commit();
session.close();
sessionFactory.close();
return SUCCESS;
}
/**
*
* @Title: edit
* @Description: 修改数据的方法
* @return void
*/
// @Test
public void edit() {
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// 得到国家
// Nation n1 = session.get(Nation.class,
// "e6a74fce-b4ae-11e8-8972-80fa5b5015f0");
// n1.setNname("Chain");
// 得到省份
// Province p1=session.get(Province.class,
// "e6a74fce-b4ae-11e8-8972-80fa5b5015f0");
// p1.setPname("Hunan");
// 得到城市
City c1 = session.get(City.class, "e6a77e3c-b4ae-11e8-8972-80fa5b5015f0");
c1.setCname("Yiyang");
transaction.commit();
session.close();
sessionFactory.close();
}
/**
*
* @Title: remove
* @Description: 删除数据的方法
* @return void
*/
// @Test
public void remove() {
Configuration configuration = new Configuration().configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// 查询国家
Nation n = session.get(Nation.class, "670dc90a-b4c3-11e8-8972-80fa5b5015f0");
session.delete(n);
transaction.commit();
session.close();
sessionFactory.close();
}