1.Hibernate属性:
<propertyname="hbm2ddl.auto">create</property>
create:表示启动的时候先drop,再create
create-drop: 也表示创建,只不过再系统关闭前执行一下drop
update: 这个操作启动的时候会去检查schema是否一致,如果不一致会做scheme更新
validate: 启动时验证现有schema与你配置的hibernate是否一致,如果不一致就抛出异常,并不做更新
2.使用hibernate集合映射方式(Set,List,Map自选)和外键同时创建两张表
需求:.通过hibernate集合映射方式(Set,List,Map自选),自动创建学生信息表和学生成绩表学生信息表字段(id,stuName,Age,Address) 学生成绩表(stuId,score) 学生成绩表的stuId和学生表Id外健关联
1) 创建model类:
publicclass Student {
private int id;
private String stuName;
private int age;
private String address;
//一个学生映射多个成绩
private Set<Double> grade = new HashSet<Double>();
…….省略get set方法
}
2) 编写映射文件
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.model.Student"table="student">
<id name="id" type="java.lang.Integer">
<column name="ID" precision="22"scale="0" />
<generator class="assigned" />
</id>
<property name="stuName" column="stuName"type="java.lang.String"></property>
<property name="age" column="age"type="java.lang.Integer"></property>
<property name="address" column="address"type="java.lang.String"></property>
<!—set的name属性需要和上面定义的model类的set的属性相同 作为grade表-->
<set name="grade" table="grade">
<keyforeign-key="id">
<column name="stuId"not-null="true"/>
</key>
<elementtype="java.lang.Double" column="grades"></element>
</set>
</class>
</hibernate-mapping>
3) 编写总的映射文件
<?xmlversion="1.0" encoding="UTF-8"?>
<!DOCTYPEhibernate-configuration PUBLIC
"-//Hibernate/HibernateConfiguration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<propertyname="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<propertyname="hibernate.connection.password">123456</property>
<propertyname="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/hiber?useUnicode=true&characterEncoding=UTF-8</property>
<propertyname="hibernate.connection.username">root</property>
<propertyname="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<propertyname="hbm2ddl.auto">create</property>
<mappingresource="com/cfg/tbl/stu.hbm.xml" />
<mappingclass="com.model.Stu" />
</session-factory>
</hibernate-configuration>
4) 编写测试类
工具类:
package com.db.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HiberDBUtil {
privatestatic String CONFIG_FILE_LOCATION="/com/cfg/hibernate.cfg.xml";
privatestatic Configuration config=new Configuration();
privatestatic SessionFactory sessionFac;
privatestatic ThreadLocal<Session> tdlocal=new ThreadLocal<Session>();
privatestatic String configfile=CONFIG_FILE_LOCATION;
//静态数据块 加载配置文件,生成sessionFactory
static{
try{
//加载配置文件
config.configure(configfile);
//通过配置文件加载sessionFactory
sessionFac=config.buildSessionFactory();
}catch(Exceptione){
e.printStackTrace();
}
}
privateHiberDBUtil(){
}
publicstatic Session getSession(){
Sessionsession=(Session)tdlocal.get();
if(null==session||!session.isOpen()){
if(sessionFac==null){
reBuildSessonFac();
}
session=(sessionFac!=null)?sessionFac.openSession():null;
tdlocal.set(session);
}
System.out.println("session:"+session);
returnsession;
}
publicstatic void reBuildSessonFac(){
try{
//加载配置文件
config.configure(configfile);
//通过配置文件加载sessionFactory
sessionFac=config.buildSessionFactory();
}catch(Exceptione){
e.printStackTrace();
}
}
publicstatic void closeSession(){
Sessionsession=tdlocal.get();
tdlocal.set(null);
if(session!=null){
session.close();
}
}
publicstatic SessionFactory getSessionFactory(){
returnsessionFac;
}
}
测试类:
package com.Test;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.db.util.HiberDBUtil;
import com.model.Student;
public class TestTwo {
publicstatic void main(String[] args) {
Set<Double>set = new HashSet<Double>();
set.add((double) 80);
set.add((double) 85);
Session session = HiberDBUtil.getSession();
Transactiontransa=session.beginTransaction();
try {
Studentstudent=new Student();
student.setId(1);
student.setStuName("hzs");
student.setAge(21);
student.setAddress("guangzhou");
student.setGrade(set);
session.save(student);
transa.commit();
} catch (Exception e) {
//ts.rollback();
} finally {
HiberDBUtil.closeSession();
}
Session session1=HiberDBUtil.getSession();
String hql = "FROM Student";
Query query =session1.createQuery(hql);
Student student = (Student)query.uniqueResult();
System.out.println(student);
session1.close();
}
}
结果:
在数据库中能够创建两张表,student表和grade表,并成功插入数据
使用注解的方式创建数据库
编写model类,填写注解:
package com.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
importorg.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="student")
public class Student {
privateint sid;
privateString sname;
// 主键:@Id 主键生成方式:strategy = "increment"
//映射表中id这个字段,不能为空,并且是唯一的
@GenericGenerator(name = "generator", strategy ="increment")
@Id
@GeneratedValue(generator = "generator")
@Column(name = "sid", unique = true, nullable =false)
publicint getSid() {
returnsid;
}
publicvoid setSid(int sid) {
this.sid= sid;
}
@Column(name = "sname", length = 50)
publicString getSname() {
returnsname;
}
publicvoid setSname(String sname) {
this.sname= sname;
}
}
编写hibernate.cfg.xml
<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/HibernateConfiguration DTD 3.0//EN"
"http://hibernate.sourceforge.net/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">123456</property>
<property name="hibernate.connection.url">jdbc:mysql://127.0.0.1:3306/hiberdb?useUnicode=true&characterEncoding=UTF-8</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="com/cfg/tbl/Pinfo.hbm.xml"/>
<mapping class="com.model.Student"/>
</session-factory>
</hibernate-configuration>
编写测试类
package com.Test;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.db.util.HiberDBUtil;
import com.model.Student;
public class TestThree {
public static void main(String[] args) {
Sessionsession =HiberDBUtil.getSession();
Transactionts = session.beginTransaction();
Studentst1 = new Student();
st1.setSname("张三");
Studentst2 = new Student();
st2.setSname("李四");
Studentst3 = new Student();
st3.setSname("王五");
session.save(st1);
session.save(st2);
session.save(st3);
session.flush();
session.clear();
Queryquery = session.createQuery(" FROM Student");
List<Student>list = query.list();
for(inti=0;i<list.size();i++){
System.out.println("student:"+list.get(i).getSname());
}
/*Personp = (Person)session.get(Person.class,2);
System.out.println(p.getName()+p.getAddress());*/
ts.commit();
HiberDBUtil.closeSession();
}
}