这个示例是为了解决关联表中有其他属性时该怎么配置、及操作。e-r图如下:
一、本例中有三个类,分别为AAA、BBB、RRR,三个类的配置代码如下:
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
@Entity
@Table(name="a")
public class AAA {
@Id
@Column(name="aid")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer aid;
private String aname;
@OneToMany(mappedBy="aaa")
private Set<RRR> rS = new HashSet<>();
public AAA(){
}
public AAA(String aname){
this.aname = aname;
}
public AAA(Integer aid ,String aname){
this.aid = aid;
this.aname = aname;
}
public Integer getAid() {
return aid;
}
public void setAid(Integer aid) {
this.aid = aid;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
public Set<RRR> getrS() {
return rS;
}
public void setrS(Set<RRR> rS) {
this.rS = rS;
}
public String toString(){
return "<aid:"+aid+" aname:"+aname+">";
}
}
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "b")
public class BBB {
@Id
@Column(name = "bid")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer bid;
private String bname;
@OneToMany(mappedBy = "bbb")
private Set<RRR> rS = new HashSet<>();
public BBB(){
}
public BBB(String bname){
this.bname = bname;
}
public BBB(Integer bid ,String bname){
this.bid = bid;
this.bname = bname;
}
public Integer getBid() {
return bid;
}
public void setBid(Integer bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public String toString() {
return "<bid:" + bid + " bname:" + bname + ">";
}
}
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="r")
public class RRR {
@EmbeddedId
private Id id = new Id();
private String rname;
@ManyToOne
@JoinColumn(name="aid",insertable=false,updatable=false)
private AAA aaa;
@ManyToOne
@JoinColumn(name="bid",insertable=false,updatable=false)
private BBB bbb;
public RRR(){
}
public RRR(String rname){
this.rname = rname;
}
public RRR(String rname,AAA aaa,BBB bbb){
this.rname = rname;
this.aaa = aaa;
this.bbb = bbb;
}
public RRR(String rname, Integer aid, Integer bid){
this.rname = rname;
this.id = new Id(aid,bid);
}
public String getRname() {
return rname;
}
public void setRname(String rname) {
this.rname = rname;
}
public AAA getAAA() {
return aaa;
}
public void setAAA(AAA aaa) {
this.aaa = aaa;
}
public BBB getBBB() {
return bbb;
}
public void setBBB(BBB bbb) {
this.bbb = bbb;
}
public String toString(){
return "<a:"+aaa.toString()+" b:"+bbb.toString()+" rname:"+rname+">";
}
@Embeddable
public static class Id implements Serializable{
@Column(name="aid")
protected Integer aid;
@Column(name="bid")
protected Integer bid;
public Id(){}
public Id(Integer aid, Integer bid){
this.aid = aid;
this.bid = bid;
}
public boolean equals(Object o){
if(o!=null && o instanceof Id){
Id that = (Id)o;
return (this.aid.equals(that.aid))&&(this.bid.equals(that.bid));
}
return false;
}
public int hashCode(){
return this.aid.hashCode() + this.bid.hashCode();
}
public Integer getAid() {
return aid;
}
public Integer getBid() {
return bid;
}
}
}
二、实例操作
1、由 已知a 得到和 a 相关联的所有b
private void findBfromA(){
Integer aid = 1;
Session sess = HibernateUtil.currentSession();
Transaction tx = sess.beginTransaction();
Query query = sess.createQuery("from AAA where aid=:aid");
query.setParameter("aid", aid);
AAA a = (AAA) query.list().get(0);
Set<RRR> rS = a.getrS();
List bList = new ArrayList<>();
for(RRR r: rS){
bList.add(r.getBBB());
}
System.out.println(bList.toString());
tx.commit();
HibernateUtil.closeSession();
}
结果示例:
[<bid:7 bname:新增b>, <bid:1 bname:b1>, <bid:2 bname:b2>, <bid:3 bname:b3>, <bid:4 bname:b4>]
2、向 r表 添加新的关联
// 向r中增加新关联
private void addToR() {
// 错误的方式
// AAA a = new AAA(1,"a1");
// BBB b = new BBB(7,"新增b");
// RRR r = new RRR("新增r");
// Session sess = HibernateUtil.currentSession();
// Transaction tx = sess.beginTransaction();
// r.setAAA(a);
// r.setBBB(b);
// sess.save(r);
// tx.commit();
// HibernateUtil.closeSession();
// 错误的方式
// AAA a = new AAA(7,"新增7");
// BBB b = new BBB(1,"b1");
// RRR r = new RRR("新增r2",a,b);
// Session sess = HibernateUtil.currentSession();
// Transaction tx = sess.beginTransaction();
// sess.save(r);
// tx.commit();
// HibernateUtil.closeSession();
// 正确的方式
RRR r = new RRR("新增r", 1, 7); //必须实例化Id类,必须设置aid、bid值,否则报错。
Session sess = HibernateUtil.currentSession();
Transaction tx = sess.beginTransaction();
sess.save(r);
tx.commit();
HibernateUtil.closeSession();
}
3、删除r表中的一条记录,两种方式
private void deleteR(){
//可以
AAA a = new AAA(1, "a1");
BBB b = new BBB(2, "b2");
Session sess = HibernateUtil.currentSession();
Transaction tx = sess.beginTransaction();
Query query = sess.createQuery("from RRR where aaa=:aaa and bbb=:bbb");
query.setParameter("aaa", a);
query.setParameter("bbb", b);
RRR r = (RRR) query.list().get(0);
sess.delete(r);
tx.commit();
HibernateUtil.closeSession();
//可以
// RRR r = new RRR("新增r", 1, 7);
// Session sess = HibernateUtil.currentSession();
// Transaction tx = sess.beginTransaction();
// sess.delete(r);
// tx.commit();
// HibernateUtil.closeSession();
}
/*
Navicat MySQL Data Transfer
Source Server : dang
Source Server Version : 50712
Source Host : 127.0.0.1:3306
Source Database : hibernate
Target Server Type : MYSQL
Target Server Version : 50712
File Encoding : 65001
Date: 2017-05-29 17:34:15
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for a
-- ----------------------------
DROP TABLE IF EXISTS `a`;
CREATE TABLE `a` (
`aid` int(11) NOT NULL AUTO_INCREMENT,
`aname` varchar(255) DEFAULT NULL,
PRIMARY KEY (`aid`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of a
-- ----------------------------
INSERT INTO `a` VALUES ('1', 'a1');
INSERT INTO `a` VALUES ('2', 'a2');
INSERT INTO `a` VALUES ('3', 'a3');
INSERT INTO `a` VALUES ('4', 'a4');
INSERT INTO `a` VALUES ('7', '新增a');
-- ----------------------------
-- Table structure for b
-- ----------------------------
DROP TABLE IF EXISTS `b`;
CREATE TABLE `b` (
`bid` int(11) NOT NULL AUTO_INCREMENT,
`bname` varchar(255) DEFAULT NULL,
PRIMARY KEY (`bid`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of b
-- ----------------------------
INSERT INTO `b` VALUES ('1', 'b1');
INSERT INTO `b` VALUES ('2', 'b2');
INSERT INTO `b` VALUES ('3', 'b3');
INSERT INTO `b` VALUES ('4', 'b4');
INSERT INTO `b` VALUES ('7', '新增b');
-- ----------------------------
-- Table structure for r
-- ----------------------------
DROP TABLE IF EXISTS `r`;
CREATE TABLE `r` (
`aid` int(11) NOT NULL,
`bid` int(11) NOT NULL,
`rname` varchar(255) DEFAULT NULL,
KEY `aid` (`aid`),
KEY `bid` (`bid`),
CONSTRAINT `aid` FOREIGN KEY (`aid`) REFERENCES `a` (`aid`) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT `bid` FOREIGN KEY (`bid`) REFERENCES `b` (`bid`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of r
-- ----------------------------
INSERT INTO `r` VALUES ('1', '1', 'r1');
INSERT INTO `r` VALUES ('1', '2', 'r2');
INSERT INTO `r` VALUES ('1', '3', 'r3');
INSERT INTO `r` VALUES ('1', '4', 'r4');
INSERT INTO `r` VALUES ('2', '1', 'r5');
INSERT INTO `r` VALUES ('2', '3', 'r6');
INSERT INTO `r` VALUES ('2', '4', 'r7');
INSERT INTO `r` VALUES ('3', '4', 'r7');
INSERT INTO `r` VALUES ('1', '7', '新增r');
四、项目地址点击打开链接