生成建表的语句
可以在配置文件进行配置,自动生成建表语句
/hibernate_0600_Status/src/hibernate.cfg.xml
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
也可以手动进行生成
用程序来建表
@Test
public void TestSchemaExport(){
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
}
去找hibernate.cfg.xml配置文件的
<mapping resource="com/zhuhw/hibernate/model/Student.hbm.xml"/>
<mapping class="com.zhuhw.hibernate.model.Teacher"/>
文件,进行生成相应的表。
create(boolean1,boolean2),第1个boolean类型是说是否覆盖原有的表,第2个boolean是说,是否新建表
运行结果:
create table Student (
id integer not null,
name varchar(255) not null,
age integer,
primary key (id, name)
)
22:47:06,947 DEBUG SchemaExport:377 -
create table Teacher (
id integer not null auto_increment,
birthdate date,
_name varchar(255),
title varchar(255),
yourWifeName varchar(255),
zhicheng integer,
primary key (id)
)
本章代码:
package com.zhuhw.hibernate.model;
import java.util.Date;
import org.hibernate.Query;
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 HibernateIDTest {
public static SessionFactory sf = null;
@BeforeClass
public static void beforeClass(){
sf = new AnnotationConfiguration().configure().buildSessionFactory();
}
@Test
public void TestStudentID(){
Student s = new Student();
/*配置文件中使用generator
* s.setId(9);
* */
StudentPK spk = new StudentPK();
spk.setId(4);
spk.setName("waxun4");
s.setAge(24);
s.setSpk(spk);
/*Session session = SessionFactory.getCurrentSession();
session.connection()*/
/*Session session = sf.openSession();
* */
Session session = sf.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
}
@Test
public void TestTeacherID(){
Teacher t = new Teacher();
/* TeacherPK tpk = new TeacherPK();
tpk.setId(1);
tpk.setName("waxun");*/
/*t.setName("yuzhou1");*/
/*t.setTpk(tpk);*/
t.setId(1);
t.setName("waxun2");
t.setTitle("ccc");
t.setBirthdate(new Date());
t.setYourWifeName("yourWifeName1");
t.setZhicheng(ZhiCheng.A);
Session session = sf.getCurrentSession();
//在hibernate中执行操作要在一个事务里面
session.beginTransaction();
System.out.println(t.getId());
session.getTransaction().commit();
}
@Test
public void TestDelete(){
Teacher t = new Teacher();
//因为id设置的自动生成,所有设置不设置是一样的
//t在这个时候是Transient状态
t.setName("t1");
t.setTitle("ccc");
t.setBirthdate(new Date());
t.setYourWifeName("yourWifeName1");
t.setZhicheng(ZhiCheng.A);
Session session = sf.getCurrentSession();
//在hibernate中执行操作要在一个事务里面
session.beginTransaction();
session.save(t);
//t这个时候是Persistent状态
System.out.println("----Persistent-------");
System.out.println(t.getId());
session.getTransaction().commit();
//t这个时候是Detached
System.out.println("---Detached--------");
System.out.println(t.getId());
//进行commit后,再进行delete()。实验一下
Session session2 = sf.getCurrentSession();
session2.beginTransaction();
session2.delete(t);
session2.getTransaction().commit();
}
@Test
public void TestDelete2(){
Teacher t = new Teacher();
t.setId(2);
Session session = sf.getCurrentSession();
session.beginTransaction();
session.delete(t);
session.getTransaction().commit();
}
@Test
public void TestSave3Status(){
Teacher t = new Teacher();
//因为id设置的自动生成,所有设置不设置是一样的
//t在这个时候是Transient状态
t.setName("t3");
t.setTitle("ccc");
t.setBirthdate(new Date());
t.setYourWifeName("yourWifeName1");
t.setZhicheng(ZhiCheng.A);
Session session = sf.getCurrentSession();
//在hibernate中执行操作要在一个事务里面
session.beginTransaction();
session.save(t);
//t这个时候是Persistent状态
System.out.println("----Persistent-------");
System.out.println(t.getId());
session.getTransaction().commit();
//t这个时候是Detached
System.out.println("---Detached--------");
System.out.println(t.getId());
}
@Test
public void TestLoad(){
//从数据库中取出一条数据到缓存中
Session session = sf.getCurrentSession();
session.beginTransaction();
//参数是第一个是转换成哪种类型,第二个参数是实现序列化的-->在这里是id,已经实现的Integer已经实现了序列化
Teacher t = (Teacher)session.load(Teacher.class, 2);
System.out.println("------------------");
System.out.println(t.getClass());
session.getTransaction().commit();
/*System.out.println("------------------");
System.out.println(t.getName());*/
}
@Test
public void TestGet(){
//从数据库中取出一条数据到缓存中
Session session = sf.getCurrentSession();
session.beginTransaction();
//参数是第一个是转换成哪种类型,第二个参数是实现序列化的-->在这里是id,已经实现的Integer已经实现了序列化
Teacher t = (Teacher)session.get(Teacher.class, 2);
//在get的时候已经进行发出sql语句了
/*System.out.println("------------------");
System.out.println(t.getName());
System.out.println(t.getYourWifeName());*/
System.out.println("------------------");
System.out.println(t.getClass());
session.getTransaction().commit();
}
@Test
public void TestUpdate1(){
//用来更新detached对象,更新完成后转为persist状态
Session session = sf.getCurrentSession();
session.beginTransaction();
Teacher t = (Teacher)session.get(Teacher.class, 2);
session.getTransaction().commit();
System.out.println("-----detached---------");
t.setName("zhuhw1111");
Session session2 = sf.getCurrentSession();
session2.beginTransaction();
session2.update(t);
System.out.println("-----persistence---------");
session2.getTransaction().commit();
}
public void TestUpdate2(){
//更新transient对象会报错,因为找不到id。
Teacher t = new Teacher();
t.setName("zhuhw1111");
Session session2 = sf.getCurrentSession();
session2.beginTransaction();
session2.update(t);
System.out.println("-----persistence---------");
session2.getTransaction().commit();
}
@Test
public void TestUpdate3(){
/*3.更新自己手动设定id的transient对象可以(前提是数据库里有这条记录)*/
Teacher t = new Teacher();
t.setId(1);
t.setName("yuzhoua111");
Session session2 = sf.getCurrentSession();
session2.beginTransaction();
session2.update(t);
System.out.println("-----persistence---------");
session2.getTransaction().commit();
}
@Test
public void TestUpdate4(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Teacher t = (Teacher)session.get(Teacher.class, 2);
//4.persistence状态的对象只要设定不同字段就会发生更新
t.setName("dooder");
session.getTransaction().commit();
}
@Test
public void TestUpdate5(){
Session session = sf.getCurrentSession();
session.beginTransaction();
Teacher t = (Teacher)session.get(Teacher.class, 2);
//在Teacher类中加入不更新的注解
t.setName("dooder_zhuhw");
session.getTransaction().commit();
}
public void TestUpdate5_1(){
//使用xml中dynamic-update
Session session = sf.getCurrentSession();
session.beginTransaction();
Student t = (Student)session.get(Student.class,1);
t.setAge(27);
session.getTransaction().commit();
}
public void TestUpdate7(){
//使用xml中dynamic-update
Session session = sf.getCurrentSession();
session.beginTransaction();
//面向对象的sql
Query q =session.createQuery("update Teacher t set t.setId=8 where id=1");
q.executeUpdate();
session.getTransaction().commit();
}
public void TestsaveORUpdate(){
Teacher t = new Teacher();
t.setName("zhuhw7");
t.setYourWifeName("yourWifeName");
Session session = sf.getCurrentSession();
session.beginTransaction();
session.saveOrUpdate(t);
session.getTransaction().commit();
t.setName("zhuhw8");
Session session2 = sf.getCurrentSession();
session2.beginTransaction();
session2.saveOrUpdate(t);
session2.getTransaction().commit();
}
@Test
public void TestClear(){
//从数据库中取出一条数据到缓存中
Session session = sf.getCurrentSession();
session.beginTransaction();
//参数是第一个是转换成哪种类型,第二个参数是实现序列化的-->在这里是id,已经实现的Integer已经实现了序列化
Teacher t = (Teacher)session.load(Teacher.class, 2);
System.out.println(t.getName());
//只执行一次sql,因为第一次执行后,将teache从缓存中取,不需要再次进行执行sql
//clear()是清除缓存,所以这时候会中2此sql
session.clear();
Teacher t2 = (Teacher)session.load(Teacher.class,2);
System.out.println(t.getName());
session.getTransaction().commit();
}
@Test
public void TestFlush(){
//从数据库中取出一条数据到缓存中
Session session = sf.getCurrentSession();
session.beginTransaction();
//参数是第一个是转换成哪种类型,第二个参数是实现序列化的-->在这里是id,已经实现的Integer已经实现了序列化
Teacher t = (Teacher)session.load(Teacher.class, 2);
//只有在进行提交了,才进行执行update语句
/* t.setName("ttt");
t.setName("ttttt");*/
//flush()强制将缓存中的数据与数据库中的数据作同步,这时会执行两天update语句
t.setName("ttt");
session.flush();
t.setName("ttttt");
session.getTransaction().commit();
}
/*也可以手动进行生成
* @Test
public void TestSchemaExport(){
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
}*/
@AfterClass
public static void afterClass(){
sf.close();
}
}
<?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> <!-- Database connection settings --> <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">root</property> <!-- <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property> <property name="connection.username">scoot</property> <property name="connection.password">tiger</property>--> <!-- JDBC connection pool (use the built-in) --> <!--<property name="connection.pool_size">1</property>--> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</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/zhuhw/hibernate/model/Student.hbm.xml"/> <mapping class="com.zhuhw.hibernate.model.Teacher"/> </session-factory> </hibernate-configuration>
package com.zhuhw.hibernate.model;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
/*1.实体类(使用annotation进行实现,告诉hibernate是实体类,
* 不需要再建立Teacher.hbm.xml文件进行映射)
* 2.hibernate.cfg.xml进行配置即可
* 3.建立一个TeacherTest
*/
@Entity
//表名和类名不同,对表名进行配置
//@Table(name = "_teacher")
//@IdClass(value=TeacherPK.class)//两个联合起来正好是一个TeacherPK.class
public class Teacher {
private int id;
private String name;
/*
3.将类注解为@IdClass,并将该实体中所有属于主键的属性都注解为@Id
将TeacherPK不用了,直接在Teacher中进行setID getID...
加注解@IdClass指明就可以,更符合编程的习惯。*/
/*private TeacherPK tpk;*/
/*@Id// 1.将组件类注解为@Embeddable,并将组件的属性注解为@Id
*/
@EmbeddedId//2.将组件的属性注解为@EmbeddedId
/*public TeacherPK getTpk() {
return tpk;
}
public void setTpk(TeacherPK tpk) {
this.tpk = tpk;
}*/
private String title;
private Date birthdate;
//ZhiCheng enum
private ZhiCheng zhicheng;
/*@Enumerated(EnumType.STRING)
* 数据库存储String
`zhicheng` varchar(255) DEFAULT NULL,
*/
/*@Enumerated(EnumType.ORDINAL)
* 数据库存储下标值
`zhicheng` varchar(255) DEFAULT NULL,*/
@Enumerated(EnumType.ORDINAL)
public ZhiCheng getZhicheng() {
return zhicheng;
}
public void setZhicheng(ZhiCheng zhicheng) {
this.zhicheng = zhicheng;
}
//映射日期与时间类型,指定时间精度
//通过@Temporal可以指定时间的精度
@Temporal(value=TemporalType.DATE)
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
private String yourWifeName;
//不要存到数据库中
/*@Transient*/
public String getYourWifeName() {
return yourWifeName;
}
public void setYourWifeName(String yourWifeName) {
this.yourWifeName = yourWifeName;
}
//主键
@Id
//ID自动生成
@GeneratedValue
public int getId() {
return id;
}
@Basic//对数据库中,字段名和属性相同
public void setId(int id) {
this.id = id;
}
//字段名属性不同a)Annotation:@Column
@Column(name = "_name")
//@Id
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/*@Column(updatable=false)*/
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
package com.zhuhw.hibernate.model;
import javax.persistence.Embeddable;
/*@Embeddable// 1.将组件类注解为@Embeddable,并将组件的属性注解为@Id
*/public class TeacherPK implements java.io.Serializable{
@Override
public boolean equals(Object o) {
if(o instanceof TeacherPK) {
TeacherPK spk = (TeacherPK)o;
if(this.id == spk.getId()&& this.name == spk.getName()){
return true;
}
}return false;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return this.name.hashCode();
}
private int id;
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;
}
private String name;
}
package com.zhuhw.hibernate.model;
import javax.persistence.Id;
public class Student {
StudentPK spk;
@Id
public StudentPK getSpk() {
return spk;
}
public void setSpk(StudentPK spk) {
this.spk = spk;
}
/* private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}*/
/*private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}*/
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/* private String name;*/
}
package com.zhuhw.hibernate.model;
public class StudentPK implements java.io.Serializable{
@Override
public boolean equals(Object o) {
if(o instanceof StudentPK) {
StudentPK spk = (StudentPK)o;
if(this.id == spk.getId()&& this.name == spk.getName()){
return true;
}
}return false;
}
@Override
public int hashCode() {
// TODO Auto-generated method stub
return this.name.hashCode();
}
private int id;
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;
}
private String name;
}
package com.zhuhw.hibernate.model;
public enum ZhiCheng {
A,B,C;
}
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- 找不到entity,是因为这个类没有改包名 --> <hibernate-mapping package="com.zhuhw.hibernate.model"> <class name="Student" dynamic-update="true"> <!-- id主键;name=id对应的是Student中的getid() --> <!--<id name="id" > <generator class="uuid"></generator> <generator class="native"></generator> </id> --> <!-- 联合组件配置 --> <composite-id name = "spk" class="com.zhuhw.hibernate.model.StudentPK"> <key-property name="id"></key-property> <key-property name="name"></key-property> </composite-id> <property name="age" /> <!-- hibernater知道了怎么将class与表中的字段对应到一起了 --> </class> </hibernate-mapping>
### 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{1}:%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