您的位置:首页 > 数据库 > MySQL

Hibernate中一对一,一对多,多对多的写法

2016-03-04 10:04 591 查看

hibernate中各类对应的bean类写法

1、一对一的情况

假设我们用Address类和User类做一对一的对应

User类

package com.telek.model;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Generated;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="user")//如果表明和对象名不一致 则需要单独加上该注解
public class User implements java.io.Serializable{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name="username")
private String username;
@Column(name="password")
private String password;
//fetch代表数据的抓取策略lazy就是指用到了该属性才会去查询(eager刚好相反)
@OneToOne(cascade = {CascadeType.ALL},fetch = FetchType.LAZY )
private Address address=new Address();

public User(){}
public User(String username,String password){
this.username = username;
this.password = password;
}

@return the address
public Address getAddress() {
return address;
}

@param address the address to set
public void setAddress(Address address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}


Address类

package com.telek.model;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="address")
public class Address {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String address;

@OneToOne(optional= false,fetch = FetchType.EAGER)//cascade = CascadeType.ALL,
@JoinColumn(name="uid")
private User user;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}

}


1、一对多的情况

假设我们用Address类和User类做一对一的对应

Address类

package com.telek.model;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="address")
public class Address {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String address;

@ManyToOne(optional= false,fetch = FetchType.EAGER)//cascade = CascadeType.ALL,
@JoinColumn(name="uid")
private User user;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}

}


User类

package com.telek.model;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Generated;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="user")//如果表明和对象名不一致 则需要单独加上该注解
public class User implements java.io.Serializable{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name="username")
private String username;
@Column(name="password")
private String password;
//fetch代表数据的抓取策略lazy就是指用到了该属性才会去查询(eager刚好相反)
@OneToMany(cascade = {CascadeType.ALL},mappedBy="user",fetch = FetchType.LAZY )
private Set<Address> address = new HashSet<Address>();

public User(){}
public User(String username,String password){
this.username = username;
this.password = password;
}

public Set<Address> getAddress() {
return address;
}
public void setAddress(Set<Address> address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}


最后,附上一对多情况中Dao包类的测试方法

public void OnetoMore(){//一对多配置
Session session = sessionFactory.openSession();
User user = new User();
user.setUsername("wjw");
user.setPassword("wlf");

Address add1 =  new Address();
add1.setAddress("浙江");
Address add2 =  new Address();
add2.setAddress("北京");

add1.setUser(user);//在多的一方告诉hibernate我这个对象属于谁
add2.setUser(user);
user.getAddress().add(add1);//在少的一端告诉hibernate我可以添加谁进来
user.getAddress().add(add2);

session.beginTransaction();
session.save(user);
session.close();
}


3、多对多的情况

假设我们用Tag类和Topic类作为演示

Tag类

package com.telek.model;
// Generated 2016-3-4 9:16:37 by Hibernate Tools 4.3.1.Final

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
* Tag generated by hbm2java
*/
@Entity
@Table(name="tag"
,catalog="springdemo"
)
public class Tag  implements java.io.Serializable {

private Integer tagid;
private String tag;
private Set<Topic> topic=new HashSet<Topic>();

public Tag() {
}

public Tag(String tag) {
this.tag = tag;
}

@Id @GeneratedValue(strategy=IDENTITY)

@Column(name="tagid", unique=true, nullable=false)
public Integer getTagid() {
return this.tagid;
}

public void setTagid(Integer tagid) {
this.tagid = tagid;
}

@Column(name="tag")
public String getTag() {
return this.tag;
}

public void setTag(String tag) {
this.tag = tag;
}

/**
* @return the topic
*/
@ManyToMany(cascade = {CascadeType.ALL},mappedBy="tag",fetch = FetchType.LAZY )
public Set<Topic> getTopic() {
return topic;
}

/**
* @param topic the topic to set
*/
public void setTopic(Set<Topic> topic) {
this.topic = topic;
}
}


Topic类

package com.telek.model;
// Generated 2016-3-4 9:16:37 by Hibernate Tools 4.3.1.Final

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

/**
* Topic generated by hbm2java
*/
@Entity
@Table(name="topic"
,catalog="springdemo"
)
public class Topic  implements java.io.Serializable {

private Integer topicid;
private String title;
private String context;
private Set<Tag> tag = new HashSet<Tag>();

public Topic() {
}

public Topic(String title, String context) {
this.title = title;
this.context = context;
}

@Id @GeneratedValue(strategy=IDENTITY)

@Column(name="topicid", unique=true, nullable=false)
public Integer getTopicid() {
return this.topicid;
}

public void setTopicid(Integer topicid) {
this.topicid = topicid;
}

@Column(name="title")
public String getTitle() {
return this.title;
}

public void setTitle(String title) {
this.title = title;
}

@Column(name="c
af66
ontext")
public String getContext() {
return this.context;
}

public void setContext(String context) {
this.context = context;
}

/**
* @return the tag
*/
@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name="topicandtag",joinColumns=@JoinColumn(name="topicid"),inverseJoinColumns=@JoinColumn(name="tagid"))
public Set<Tag> getTag() {
return tag;
}

/**
* @param tag the tag to set
*/
public void setTag(Set<Tag> tag) {
this.tag = tag;
}
}


最后在Dao里面写一个方法作为演示

public void ManyToMany(){
Session session = sessionFactory.openSession();
Topic topic = new Topic();
topic.setTitle(("大保健"));
topic.setContext("来玩来玩");
Topic topic2 = new Topic();
topic2.setTitle(("大保健"));
topic2.setContext("来玩来玩呀");
Tag tag1 = new Tag();tag1.setTag("服务");
Tag tag2 = new Tag();tag2.setTag("保健");

Set<Tag> tags = new HashSet<Tag>();
tags.add(tag1);tags.add(tag2);
topic.setTag(tags);

Set<Topic> topics = new HashSet<Topic>();
topics.add(topic);
topics.add(topic2);
tag1.setTopic(topics);
tag2.setTopic(topics);

session.beginTransaction();
session.save(topic);
session.getTransaction().commit();
session.close();
}


发现关系表和Tag表和Topic表都插入数据为正常

最后,附上数据库表的情况



另外,如果在topic和tag两边都加上

@ManyToMany(cascade = {CascadeType.ALL})
@JoinTable(name="topicandtag",joinColumns=@JoinColumn(name="tagid"),inverseJoinColumns=@JoinColumn(name="topicid"))


即可以不用两边set关系,只用一边关联就可以两边都存入数据库
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hibernate mysql