1.新建一个工具类
2.编写代码
package cn.happy.day01.util; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; /** * Created by CY on 2017/12/23. */ public class HibernateUtil { private static ThreadLocal<Session> tl=new ThreadLocal<Session>(); private static Configuration cfg; private static SessionFactory sessionFactory; static { cfg=new Configuration().configure(); sessionFactory=cfg.buildSessionFactory(); } public static Session getSession(){ Session session=tl.get(); if(session==null){ session = sessionFactory.openSession(); tl.set(session); } return session; } public static void closeSession(){ Session session = (Session) tl.get(); tl.set(null); session.close(); } }
注意这里使用的是openSession();
3.大配置小配置:不用解了
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <!----> <session-factory> <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">happy</property> <property name="connection.password">happy</property> <!--sql 方言--> <property name="dialect">org.hibernate.dialect.Oracle10gDialect</property> <!--连接池--> <!--<property name="connection.pool_size">1</property>--> <!--和当前线程绑定--> <property name="current_session_context_class">thread</property> <!--echo 打印控制台语句 shout--> <property name="show_sql">true</property> <!--格式化代码--> <property name="format_sql">true</property> <!--自动更新表结构 createe 先delete表结构 在创建 update直接更新表结构--> <property name="hbm2ddl.auto">update</property> <mapping resource="cn/happy/day01/entity/Dog.hbm.xml" /> <mapping resource="cn/happy/day01/entity/Student.hbm.xml" /> </session-factory> </hibernate-configuration>
@Entity public class Student { private Integer sid; private String sname; private Integer sage;
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.happy.day01.entity"> <class name="Student" table="STUDENT" schema="happy"> <id name="sid" column="sid"> <!-- native 数据库方言的可移植性 --> <generator class="native"/> </id> <property name="sname" column="sname" /> <property name="sage" column="sage"/> </class> </hibernate-mapping>
4.数据库使用的是Oracle
/*
Navicat Oracle Data Transfer
Oracle Client Version : 11.2.0.1.0
Source Server : happy
Source Server Version : 110200
Source Host : localhost:1521
Source Schema : HAPPY
Target Server Type : ORACLE
Target Server Version : 110200
File Encoding : 65001
Date: 2017-12-24 22:31:33
*/
-- ----------------------------
-- Table structure for STUDENT
-- ----------------------------
DROP TABLE "HAPPY"."STUDENT";
CREATE TABLE "HAPPY"."STUDENT" (
"SID" NUMBER(10) NOT NULL ,
"SNAME" VARCHAR2(255 CHAR) NULL ,
"SAGE" NUMBER(10) NULL
)
LOGGING
NOCOMPRESS
NOCACHE
;
-- ----------------------------
-- Records of STUDENT
-- ----------------------------
INSERT INTO "HAPPY"."STUDENT" VALUES ('4', '小红', '12');
-- ----------------------------
-- Indexes structure for table STUDENT
-- ----------------------------
-- ----------------------------
-- Checks structure for table STUDENT
-- ----------------------------
ALTER TABLE "HAPPY"."STUDENT" ADD CHECK ("SID" IS NOT NULL);
-- ----------------------------
-- Primary Key structure for table STUDENT
-- ----------------------------
ALTER TABLE "HAPPY"."STUDENT" ADD PRIMARY KEY ("SID");
5.使用的jar包
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <parent> <artifactId>Y2166</artifactId> <groupId>cn.happy</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>hibernate</artifactId> <packaging>war</packaging> <name>hibernate Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.3</version> <scope>test</scope> </dependency> <!--oracle jdbc--> <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.1.0</version> </dependency> <!--hibernate核心jar--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.0.6.Final</version> </dependency> <!--oracle 事务--> <dependency> <groupId>javax.transaction</groupId> <artifactId>jta</artifactId> <version>1.1</version> </dependency> <!--mysql数据库驱动--> <dependency> <groupId>org.wisdom-framework</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.34_1</version> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.*</include> </includes> </resource> </resources> </build> </project>
6.测试类
数据库修改前:
测试修改
package day02hql; import cn.happy.day01.entity.Student; import cn.happy.day01.util.HibernateUtil; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.List; /** * 脏检查和缓存机制探讨 */ public class mytest20171224_02 { Configuration cfg; SessionFactory factory; Session session; Transaction tx; @Before public void before(){ cfg=new Configuration().configure(); factory=cfg.buildSessionFactory(); session=factory.getCurrentSession(); tx=session.beginTransaction(); } @Test public void t1(){ //使用update更新数据 Student student = session.load(Student.class, 4); student.setSname("小贱贱"); session.update(student); tx.commit(); //在数据同步情况下更新数据 Student student1 = HibernateUtil.getSession().load(Student.class, 4); student1.setSname("小军"); HibernateUtil.closeSession(); } }
数据库运行后
运行结果:
可以看到数据库确实是更新了
但是控制台却打印出来两条查询语句
E:jdkinjava -ea -Didea.launcher.port=7535 "-Didea.launcher.bin.path=E:ideatIntelliJ IDEA 2016.3.2in" -Dfile.encoding=UTF-8 -classpath "E:ideatIntelliJ IDEA 2016.3.2libidea_rt.jar;E:ideatIntelliJ IDEA 2016.3.2pluginsjunitlibjunit-rt.jar;E:jdkjrelibcharsets.jar;E:jdkjrelibdeploy.jar;E:jdkjrelibextaccess-bridge-32.jar;E:jdkjrelibextcldrdata.jar;E:jdkjrelibextdnsns.jar;E:jdkjrelibextjaccess.jar;E:jdkjrelibextjfxrt.jar;E:jdkjrelibextlocaledata.jar;E:jdkjrelibext ashorn.jar;E:jdkjrelibextsunec.jar;E:jdkjrelibextsunjce_provider.jar;E:jdkjrelibextsunmscapi.jar;E:jdkjrelibextsunpkcs11.jar;E:jdkjrelibextzipfs.jar;E:jdkjrelibjavaws.jar;E:jdkjrelibjce.jar;E:jdkjrelibjfr.jar;E:jdkjrelibjfxswt.jar;E:jdkjrelibjsse.jar;E:jdkjrelibmanagement-agent.jar;E:jdkjrelibplugin.jar;E:jdkjrelib esources.jar;E:jdkjrelib t.jar;E:Y2166hibernate arget est-classes;E:Y2166hibernate argetclasses;E:mavon epositoryjunitjunit4.3junit-4.3.jar;E:mavon epositorycomoracleojdbc611.2.0.1.0ojdbc6-11.2.0.1.0.jar;E:mavon epositoryorghibernatehibernate-core5.0.6.Finalhibernate-core-5.0.6.Final.jar;E:mavon epositoryorgjbossloggingjboss-logging3.3.0.Finaljboss-logging-3.3.0.Final.jar;E:mavon epositoryorghibernatejavaxpersistencehibernate-jpa-2.1-api1.0.0.Finalhibernate-jpa-2.1-api-1.0.0.Final.jar;E:mavon epositoryorgjavassistjavassist3.18.1-GAjavassist-3.18.1-GA.jar;E:mavon epositoryantlrantlr2.7.7antlr-2.7.7.jar;E:mavon epositoryorgjbossjandex2.0.0.Finaljandex-2.0.0.Final.jar;E:mavon epositorydom4jdom4j1.6.1dom4j-1.6.1.jar;E:mavon epositoryxml-apisxml-apis1.0.b2xml-apis-1.0.b2.jar;E:mavon epositoryorghibernatecommonhibernate-commons-annotations5.0.1.Finalhibernate-commons-annotations-5.0.1.Final.jar;E:mavon epositoryjavax ransactionjta1.1jta-1.1.jar;E:mavon epositoryorgwisdom-frameworkmysql-connector-java5.1.34_1mysql-connector-java-5.1.34_1.jar;E:mavon epositoryorgapachefelixorg.apache.felix.ipojo.annotations1.12.1org.apache.felix.ipojo.annotations-1.12.1.jar;E:mavon epositoryorgwisdom-frameworkabstract-jdbc-driver .5abstract-jdbc-driver-0.5.jar" com.intellij.rt.execution.application.AppMain com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 day02hql.mytest20171224_02,t1 十二月 24, 2017 10:36:14 下午 org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {5.0.6.Final} 十二月 24, 2017 10:36:14 下午 org.hibernate.cfg.Environment <clinit> INFO: HHH000206: hibernate.properties not found 十二月 24, 2017 10:36:14 下午 org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist 十二月 24, 2017 10:36:14 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final} 十二月 24, 2017 10:36:15 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) 十二月 24, 2017 10:36:15 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001005: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:@localhost:1521:orcl] 十二月 24, 2017 10:36:15 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001001: Connection properties: {user=happy, password=****} 十二月 24, 2017 10:36:15 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001003: Autocommit mode: false 十二月 24, 2017 10:36:15 下午 org.hibernate.engine.jdbc.connections.internal.PooledConnections <init> INFO: HHH000115: Hibernate connection pool size: 20 (min=1) 十二月 24, 2017 10:36:16 下午 org.hibernate.dialect.Dialect <init> INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect 十二月 24, 2017 10:36:16 下午 org.hibernate.id.UUIDHexGenerator <init> WARN: HHH000409: Using org.hibernate.id.UUIDHexGenerator which does not generate IETF RFC 4122 compliant UUID values; consider using org.hibernate.id.UUIDGenerator instead 十二月 24, 2017 10:36:17 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000228: Running hbm2ddl schema update Hibernate: select student0_.sid as sid1_1_0_, student0_.sname as sname2_1_0_, student0_.sage as sage3_1_0_ from happy.STUDENT student0_ where student0_.sid=? 十二月 24, 2017 10:36:18 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) 十二月 24, 2017 10:36:18 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001005: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:@localhost:1521:orcl] 十二月 24, 2017 10:36:18 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001001: Connection properties: {user=happy, password=****} 十二月 24, 2017 10:36:18 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001003: Autocommit mode: false 十二月 24, 2017 10:36:18 下午 org.hibernate.engine.jdbc.connections.internal.PooledConnections <init> INFO: HHH000115: Hibernate connection pool size: 20 (min=1) 十二月 24, 2017 10:36:18 下午 org.hibernate.dialect.Dialect <init> INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect 十二月 24, 2017 10:36:18 下午 org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000228: Running hbm2ddl schema update Hibernate: select student0_.sid as sid1_1_0_, student0_.sname as sname2_1_0_, student0_.sage as sage3_1_0_ from happy.STUDENT student0_ where student0_.sid=? Process finished with exit code 0
?待讨论