本文章中的方法不适用于springboot2.X版本,springboot2.X相对springboot1.X中依赖包多处发生改变。
springboot2.X集成hibernate5自定义sessionfactory工厂实现数据库操作
由于刚开始学习使用springboot,整合hibernate,刚开始在网上找了太多的例子都是整合spring data JPA的方式,于是在这里记录一下自己整合hibernate的蒙蔽(艰辛)过程
1. 创建一个maven项目,导入相关依赖
这里使用IDEA直接生成springboot项目
<!-- 添加web依赖,使用内置tomcat容器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 添加JPA依赖,官网描述支持spring data JPA 和hibernate-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--导入连接MySQL的依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- 导入测试包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2. 配置数据源相关设置
指定Tomcat启动端口号,由于本机8080已占用,暂用80端口
server.port=80
#mysql
spring.datasource.url=jdbc:mysql://localhost:3306/springboot01?useunicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
# 指定数据库类型
spring.jpa.database = MYSQL
# 是否展示SQL
spring.jpa.show-sql = true
# hibernate自动建表
spring.jpa.hibernate.ddl-auto = update
#命名策略
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
3. 编写实体类与表的映射
package com.jx.springboot.base;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "User")
public class BaseUser implements Serializable {
@Id //指定实体类属性为表ID字段
@GeneratedValue(strategy = GenerationType.IDENTITY)//指定ID生成策略为自增长
private Integer userID;
@Column(name = "userName")//指定属性与表字段名对应关系
private String userName;
@Column(name = "passWord")
private String passWord;
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
public Integer getUserID() {
return userID;
}
public void setUserID(Integer userID) {
this.userID = userID;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
4. 编写配置类,配置sessionfactory实例到spring容器``
package com.jx.springboot.config;
import org.hibernate.SessionFactory;
import org.hibernate.jpa.HibernateEntityManagerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class HibernateConfig {
@Bean()
SessionFactory sessionFactory(HibernateEntityManagerFactory hibernateEntityManagerFactory){
return hibernateEntityManagerFactory.getSessionFactory();
}
}
5.编写DAO类
@Repository
public class UserDao{
//注入sessionfactory
@Autowired
private SessionFactory sessionFactory;
public User findByID(Integer userID) {
User user = sessionFactory.openSession().get(User.class,userID);
return user;
}
}
6. 这里省略service层 直接在controller类调用DAO
@RestController
public class HelloController {
//注入DAO
@Autowired
private UserDao userDao;
@RequestMapping("/hello/{userID}")
public User hello(@PathVariable Integer userID){
User user = userDao.findByID(userID);
return user;
}
}
7. 启动主类,浏览器测试结果
package com.jx.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
测试结果:
另外通过下面的方式也能获取sessionFactory ,上面的HibernateEntityManagerFactory接口继承了EntityManagerFactory接口
import javax.persistence.EntityManagerFactory;
User user2 = entityManagerFactory.unwrap(SessionFactory.class).openSession().get(User.class,userID);
摸索的过程中似乎还有一种,但是浏览器请求的时候第一次正常返回数据,第二次500了,后台报了个entityManager啥啥的被关闭了,具体忘了…
最后还有一点搞不懂的地方在于不写sessionfactory配置类,直接在DAO里注入是空值,如果写配置类不通过上面的方式,直接返回sessionFactory会报 “同名” 的错误,目前还处于蒙蔽状态…