Hibernate学习笔记 --- 使用Hibernate连接数据库
Posted smart_妖
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Hibernate学习笔记 --- 使用Hibernate连接数据库相关的知识,希望对你有一定的参考价值。
Hibernate用来操作数据库,它对开发人员隐藏了底层JDBC的操作及不同数据库的差异,通过它,开发人员基本上只用关心自己的对象就可以了
构建一个最基本的Hibernate应用需要四个部分:
1.数据类。数据类同数据库的表存在对应关系,使用Hibernate操作数据类时,Hibernate会将之转换为对数据库中对应表的操作;
2.ORM配置文件,用于配置数据类及数据库中表的对应关系;
3.Hibernate配置文件,用于配置JDBC数据源、ORM配置文件路径等信息;
4.程序启动类,用于加载Hibernate并启动整个应用;
以一个基于maven的项目为例,其项目结构示例如下,该项目将创建一个电影表用来管理电影数据
首先,在pom.xml中配置Hibernate相关的依赖
1 <dependencies> 2 <!-- Hibernate依赖 --> 3 <dependency> 4 <groupId>org.hibernate</groupId> 5 <artifactId>hibernate-core</artifactId> 6 <version>5.2.11.Final</version> 7 </dependency> 8 9 <!-- JDBC驱动的依赖,不使用mysql换成对应的驱动 --> 10 <dependency> 11 <groupId>mysql</groupId> 12 <artifactId>mysql-connector-java</artifactId> 13 <version>8.0.8-dmr</version> 14 </dependency> 15 </dependencies> 16 17 <build> 18 <resources> 19 <resource> 20 <directory>${basedir}/src/main/resources</directory> 21 </resource> 22 <!-- 由于ORM配置文件放在src/main/java目录下,maven默认不会将该目录下非java文件打包,还需做该配置 --> 23 <resource> 24 <directory>${basedir}/src/main/java</directory> 25 <includes> 26 <include>**/*.hbm.xml</include> 27 </includes> 28 </resource> 29 </resources> 30 </build>
其次,编写数据类Movie.java,其内包含ID、电影名称及描述信息
1 package study.hibernate.model; 2 3 /** 4 * 电影数据类 5 * @author yaoyao 6 * 7 */ 8 public class Movie { 9 private int id; 10 11 private String name; 12 13 private String description; 14 15 public int getId() { 16 return id; 17 } 18 19 public void setId(int id) { 20 this.id = id; 21 } 22 23 public String getName() { 24 return name; 25 } 26 27 public void setName(String name) { 28 this.name = name; 29 } 30 31 public String getDescription() { 32 return description; 33 } 34 35 public void setDescription(String description) { 36 this.description = description; 37 } 38 39 }
接着,编写ORM配置文件Movie.hbm.xml,用于告诉Hibernate,该数据类同数据库中哪个表对应,该表的数据结构是什么样的
<?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="study.hibernate.model"> <!-- 此处配置的class name与上面的package合并得到完整的类名 --> <class name="Movie" table="Movie"> <!-- MOVIE_ID列作为MOVIE表的主键,同Movie类的id属性关联 --> <id name="id" column="MOVIE_ID" /> <!-- string类型对应的数据库类型为VARCHAR(255),可以存储255个字符 --> <property name="name" type="string" column="NAME" /> <!-- desc属性比较长,字段类型需设置为text,最多可以存储2^32 - 1个字符 --> <property name="description" type="text" column="DESCRIPTION" /> </class> </hibernate-mapping>
接下来,编写Hibernate配置文件,配置JDBC、ORM配置文件 路径等相关信息
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configuration PUBLIC 3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5 6 <hibernate-configuration> 7 <session-factory> 8 <!-- 数据库JDBC配置 --> 9 <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property> 10 <property name="connection.url">jdbc:mysql://localhost:3306/MOVIE_DB?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8</property> 11 <property name="connection.username">root</property> 12 <property name="connection.password">root</property> 13 14 <!-- JDBC数据库连接池大小 --> 15 <property name="connection.pool_size">10</property> 16 17 <!-- SQL dialect --> 18 <!-- <property name="dialect">org.hibernate.dialect.H2Dialect</property> --> 19 <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> 20 21 <!-- Disable the second-level cache --> 22 <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> 23 24 <!-- Echo all executed SQL to stdout --> 25 <property name="show_sql">true</property> 26 27 <!-- 每次启动的时候,会把表先删除重新创建 --> 28 <property name="hbm2ddl.auto">create</property> 29 30 <!-- 数据类和表关联关系文件存放路径,Hibernate会在整个classpath下查找该文件 --> 31 <mapping resource="study/hibernate/model/Movie.hbm.xml"/> 32 33 </session-factory>
最后,编写程序启动类Launcher.java,加载Hibernate并启动应用程序
1 package study.hibernate; 2 3 import org.hibernate.Session; 4 import org.hibernate.SessionFactory; 5 import org.hibernate.boot.MetadataSources; 6 import org.hibernate.boot.registry.StandardServiceRegistry; 7 import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 8 9 import study.hibernate.model.Movie; 10 11 public class Launcher { 12 public static void main(String[] args) { 13 StandardServiceRegistry registry = new StandardServiceRegistryBuilder() 14 .configure() 15 .build(); 16 SessionFactory sessionFactory = null; 17 Session session = null; 18 try { 19 sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory(); 20 session = sessionFactory.openSession(); 21 22 Movie movie = new Movie(); 23 movie.setId(1); 24 movie.setName("速度与激情8"); 25 movie.setDescription("多米尼克(范·迪塞尔 Vin Diesel 饰)与莱蒂(米歇尔·罗德里格兹 Michelle Rodriguez 饰)共度蜜月,布莱恩与米娅退出了赛车界,这支曾环游世界的顶级飞车家族队伍的生活正渐趋平淡。然而,一位神秘女子Cipher(查理兹·塞隆 Charlize T heron 饰)的出现,令整个队伍卷入信任与背叛的危机,面临前所未有的考验。"); 26 27 session.beginTransaction(); 28 session.save(movie); 29 session.getTransaction().commit(); 30 } catch (Exception e) { 31 e.printStackTrace(); 32 } finally { 33 if (session != null) { 34 session.close(); 35 } 36 37 if(sessionFactory != null) { 38 sessionFactory.close(); 39 } 40 } 41 } 42 }
运行程序,并查看数据,发现数据库中已经创建了movie表并且其内已经插入了一条数据
mysql> use MOVIE_DB; Database changed mysql> select name from Movie; +------------------+ | name | +------------------+ | 速度与激情8 | +------------------+ 1 row in set (0.00 sec) mysql>
学习过程中遇到的一些问题:
1.MYSQL使用的是5.7版本,而JDBC使用的最新的8.0.8版本,启动的时候提示时区信息不可识别
Caused by: java.sql.SQLException: The server time zone value \'Öйú±ê׼ʱ¼ä\' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support. at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:121) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:89) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:81) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:55) at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:65) at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:70) at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:853) at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:440) at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:241) at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:221) at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:38) ... 28 more
该问题在hibrnate.cfg.xml中指定时区(GMT+8,其中+需用%2B转义)信息即可:jdbc:mysql://localhost:3306/MOVIE_DB?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8
2.Hibernae官方基础示例中配置的方言为org.hibernate.dialect.H2Dialect,需更改为正确的方言配置org.hibernate.dialect.MySQL5Dialect,否则会提示DDL语句执行失败
WARN: GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:424) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:315) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:155) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:313) at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452) at org.hibernate.boot.internal.MetadataImpl.buildSessionFactory(MetadataImpl.java:170) at study.hibernate.Launcher.main(Launcher.java:19)
3.Hibernate.cfg.xml中的<property name="hbm2ddl.auto">create</property>配置只会自动创表,不会帮忙把schemal一起创建出来,因此程序运行前必须手动创建:create database MOVIE_DB;
以上是关于Hibernate学习笔记 --- 使用Hibernate连接数据库的主要内容,如果未能解决你的问题,请参考以下文章
websphere启动报/WEB-INF/applicationContext-orm- hibernate.xml]: Could not resolve placeholder 'hibe