Hibernate学习笔记(一) --- 使用Hibernate连接数据库

Hibernate用来操作数据库,它对开发人员隐藏了底层JDBC的操作及不同数据库的差异,通过它,开发人员基本上只用关心自己的对象就可以了
构建一个最基本的Hibernate应用需要四个部分:
1.数据类。数据类同数据库的表存在对应关系,使用Hibernate操作数据类时,Hibernate会将之转换为对数据库中对应表的操作;
2.ORM配置文件,用于配置数据类及数据库中表的对应关系;
3.Hibernate配置文件,用于配置JDBC数据源、ORM配置文件路径等信息;
4.程序启动类,用于加载Hibernate并启动整个应用;
以一个基于maven的项目为例,其项目结构示例如下,该项目将创建一个电影表用来管理电影数据
首先,在pom.xml中配置Hibernate相关的依赖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
其次,编写数据类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,该数据类同数据库中哪个表对应,该表的数据结构是什么样的
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
接下来,编写Hibernate配置文件,配置JDBC、ORM配置文件 路径等相关信息
1
2
3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4 "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
最后,编写程序启动类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.
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.
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中的