hibernate 一对多双向的CURD
转自尚学堂教学视频
package com.bjsxt.hibernate;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="t_group")
public class Group {
private int id;
private String name;
private Set<User> users = new HashSet<User>();
@Id
@GeneratedValue
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;
}
@OneToMany(mappedBy="group",
cascade={CascadeType.ALL}//级联,对user的任何增删改操作都会影响到该表
)//还有一个属性fetch=FetchType.EAGER/LAZY 设置了可以控制查询该表的时候是否把它关联表中它关联的部分的内容也都查出来。
//一对多中,一默认的是LAZY就是不取,多默认的是EAGER就是取关联表的内容
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
package com.bjsxt.hibernate;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name="t_user")
public class User {
private int id;
private String name;
private Group group;
@ManyToOne(cascade={CascadeType.ALL})
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
@Id
@GeneratedValue
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;
}
}
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">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">bjsxt</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!--
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:SXT</property>
<property name="connection.username">scott</property>
<property name="connection.password">tiger</property>
<property name="dialect">org.hibernate.dialect.OracleDialect</property>
-->
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup
<property name="hbm2ddl.auto">update</property>
-->
<!--
<mapping resource="com/bjsxt/hibernate/Group.hbm.xml"/>
<mapping resource="com/bjsxt/hibernate/User.hbm.xml"/>
-->
<mapping class="com.bjsxt.hibernate.Group"/>
<mapping class="com.bjsxt.hibernate.User"/>
</session-factory>
</hibernate-configuration>
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=warn, stdout
#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug
### log HQL query parser activity
#log4j.logger.org.hibernate.hql.ast.AST=debug
### log just the SQL
#log4j.logger.org.hibernate.SQL=debug
### log JDBC bind parameters ###
#log4j.logger.org.hibernate.type=info
#log4j.logger.org.hibernate.type=debug
### log schema export/update ###
log4j.logger.org.hibernate.tool.hbm2ddl=debug
### log HQL parse trees
#log4j.logger.org.hibernate.hql=debug
### log cache activity ###
#log4j.logger.org.hibernate.cache=debug
### log transaction activity
#log4j.logger.org.hibernate.transaction=debug
### log JDBC resource acquisition
#log4j.logger.org.hibernate.jdbc=debug
### enable the following line if you want to track down connection ###
### leakages when using DriverManagerConnectionProvider ###
#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
测试例子代码:
package com.bjsxt.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class HibernateORMappingTest {
private static SessionFactory sessionFactory;
@BeforeClass
public static void beforeClass() {
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
@AfterClass
public static void afterClass() {
sessionFactory.close();
}
@Test
public void testSaveUser() {
User u = new User();
u.setName("u1");
Group g = new Group();
g.setName("g1");
u.setGroup(g);
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
//s.save(g);
s.save(u);
s.getTransaction().commit();
}
@Test
public void testSaveGroup() {
User u1 = new User();
u1.setName("u1");
User u2 = new User();
u2.setName("u2");
Group g = new Group();
g.setName("g1");
g.getUsers().add(u1);
g.getUsers().add(u2);
u1.setGroup(g);
u2.setGroup(g);
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
//s.save(g);
s.save(g);
s.getTransaction().commit();
}
@Test
public void testGetUser() {
testSaveGroup();
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
User u = (User)s.get(User.class, 1);
s.getTransaction().commit();
System.out.println(u.getGroup().getName());//a,这个时候是会报错的,因为session已经关闭了
}
@Test
public void testLoadUser() {
testSaveGroup();
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
User u = (User)s.load(User.class, 1);
System.out.println(u.getGroup().getName());//b,放在里面就不会,
//虽然没有在fetch中设置eager没有取出来但是当你使用的时候只要session没有关闭,还是会去数据库中取你要的内容,这点load和get一样。
s.getTransaction().commit();
}
@Test
public void testDeleteUser() {
testSaveGroup();
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
//User u = (User)s.load(User.class, 1);
//u.setGroup(null);
//s.delete(u);
s.createQuery("delete from User u where u.id = 1").executeUpdate();
s.getTransaction().commit();
}
@Test
public void testDeleteGroup() {
testSaveGroup();
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
//User u = (User)s.load(User.class, 1);
//u.setGroup(null);
//s.delete(u);
Group g = (Group)s.load(Group.class, 1);
s.delete(g);
//s.createQuery("delete from User u where u.id = 1").executeUpdate();
s.getTransaction().commit();
}
@Test
public void testUpdateUser() {
testSaveGroup();
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
User u = (User)s.get(User.class, 1);
s.getTransaction().commit();
u.setName("user");
u.getGroup().setName("group");
Session s2 = sessionFactory.getCurrentSession();
s2.beginTransaction();
s2.update(u);
s2.getTransaction().commit();
}
@Test
public void testGetGroup() {
testSaveGroup();
Session s = sessionFactory.getCurrentSession();
s.beginTransaction();
Group g = (Group)s.get(Group.class, 1);
s.getTransaction().commit();
for(User u : g.getUsers()) {
System.out.println(u.getName());
}
}
@Test
public void testSchemaExport() {
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
}
public static void main(String[] args) {
beforeClass();
}
}