SpringBoots使用Hibernate连接数据库。
环境:IDea
springBoot版本:2.1.7
Oracle 11g
中间件:tomcat8(使用8以下的版本在运行程序时会出现一些问题)
项目结构,如图:
使用到的jar包列表(要特别注意引用的jar包的版本,博主在整合hibernate时由于引入的jar包版本不合适,出了好多问题。)
配置文件:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- 地址为http://localhost:8080/ 显示的默认网页-->
<welcome-file-list>
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/applicationContext.xml</param-value>
</context-param>
<!-- spring MVC config start-->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 此处指向的的是SpringMVC的配置文件 -->
<param-value>classpath:config/spring-mvc.xml</param-value>
</init-param>
<!--配置容器在启动的时候就加载这个servlet并实例化-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- spring MVC config end-->
<!-- Spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 字符集过滤 -->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<absolute-ordering />
</web-app>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--********************************************配置Spring*************************************** -->
<!-- 自动扫描 -->
<context:component-scan base-package="com.ssh">
<!-- 扫描时跳过 @Controller 注解的JAVA类(控制器) -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--********************************************配置hibernate******************************************** -->
<!--扫描配置文件(这里指向的是之前配置的那个config.properties) -->
<!-- <context:property-placeholder location="config.properties" /> -->
<!--配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="oracle.jdbc.driver.OracleDriver" /> <!--数据库连接驱动 -->
<property name="jdbcUrl" value="jdbc:oracle:thin:@192.168.74.128:1521:ora11g" /> <!--数据库地址 -->
<property name="user" value="scott" /> <!--用户名 -->
<property name="password" value="tiger" /> <!--密码 -->
<property name="maxPoolSize" value="40" /> <!--最大连接数 -->
<property name="minPoolSize" value="20" /> <!--最小连接数 -->
<property name="initialPoolSize" value="10" /> <!--初始化连接池内的数据库连接 -->
<!-- <property name="maxIdleTime" value="20" /> <!–最大空闲时间 –>-->
</bean>
<!--配置session工厂 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- <property name="packagesToScan" value="com.ssh.entity" /> -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop> <!--指定数据库方言 -->
<prop key="hibernate.show_sql">true</prop> <!--在控制台显示执行的数据库操作语句 -->
<prop key="hibernate.format_sql">false</prop> <!--在控制台显示执行的数据哭操作语句(格式) -->
</props>
</property>
<property name="mappingLocations">
<list>
<value>classpath:config/Person.hbm.xml
</value>
</list>
</property>
</bean>
<!-- 事物管理器配置 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- 启动注解驱动的spring MVC功能,注册请求url和注解POJO类方法的映射-->
<mvc:annotation-driven />
<!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
<context:component-scan base-package="com.ssh" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="views/" /> <!-- 前缀 -->
<property name="suffix" value=".jsp" /> <!-- 后缀 -->
</bean>
</beans>
Person.hbm.xml
<?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">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.ssh.entity.Person" table="hello">
<id name="dbserno" type="java.lang.Integer">
<column name="DBSERNO" precision="22" scale="0" />
<generator class="sequence" >
<param name="sequence">HELLO_SEQ</param>
</generator>
</id>
<!-- <id name="dbserno" type="Long" column="DBSERNO">
<generator class="sequence">
<param name="sequence">HELLO_SEQ</param>
</generator>
</id>-->
<property name="name" type="java.lang.String">
<column name="name" length="20" />
</property>
<property name="age" type="java.lang.String">
<column name="age" length="3" />
</property>
<property name="descript" type="java.lang.String">
<column name="descript" length="200"/>
</property>
</class>
</hibernate-mapping>
applications.properties
spring.mvc.view.prefix=/view/
spring.mvc.view.suffix=.jsp
数据库代码
-- Create table
create table HELLO
(
name VARCHAR2(20),
age VARCHAR2(3),
descript VARCHAR2(200),
dbserno NUMBER not null,
)
tablespace USERS
pctfree 10
initrans 1
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
-- Create/Recreate primary, unique and foreign key constraints
alter table HELLO
add constraint DBSERNO primary key (DBSERNO)
using index
tablespace USERS
pctfree 10
initrans 2
maxtrans 255
storage
(
initial 64K
next 1M
minextents 1
maxextents unlimited
);
具体代码:
MainController:
package com.ssh.controller;
import com.ssh.entity.Person;
import com.ssh.service.PersonService;
import com.ssh.service.TestService;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ssh.service.TestService;
@Controller
public class MainController {
@Autowired
private TestService testService;
@Autowired
private PersonService personService;
@RequestMapping(value = "test", method = RequestMethod.GET)
public String test() {
// ʵ�ʷ��ص���views/test.jsp ,spring-mvc.xml�����ù�ǰ��
return "test";
}
@RequestMapping(value = "springtest", method = RequestMethod.GET)
public String springTest() {
return testService.test();
}
// @PostMapping("savePerson")
@RequestMapping(value = "savePerson", method = RequestMethod.GET)
@ResponseBody
public String savePerson() {
System.out.println("��ʼ����savePerson");
Integer i = personService.savePerson();
System.out.println(i);
return "success";
}
}
Person
package com.ssh.entity;
import javax.persistence.*;
public class Person
{
private Integer dbserno;
private String name;
private String age;
private String descript;
public Person() {
}
public Integer getDbserno() {
return dbserno;
}
public void setDbserno(Integer dbserno) {
this.dbserno = dbserno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getDescript() {
return descript;
}
public void setDescript(String descript) {
this.descript = descript;
}
}
PersonRepositoryImpl
package com.ssh.respository.impl;
import com.ssh.entity.Person;
import com.ssh.respository.PersonRepository;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public class PersonRepositoryImpl implements PersonRepository {
@Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return this.sessionFactory.openSession();
}
public Person load(Integer id) {
return (Person)getCurrentSession().load(Person.class,id);
}
public Person get(Integer id) {
return (Person)getCurrentSession().get(Person.class,id);
}
public List<Person> findAll() {
return null;
}
public void persist(Person entity) {
getCurrentSession().persist(entity);
}
public Integer save(Person entity) {
Session session = getCurrentSession();
Transaction transaction = session.beginTransaction();
int i = (Integer) session.save(entity);
transaction.commit();
return i;
}
public void saveOrUpdate(Person entity) {
Transaction transaction = getCurrentSession().beginTransaction();
getCurrentSession().saveOrUpdate(entity);
transaction.commit();
}
public void delete(Integer id) {
Person person = load(id);
getCurrentSession().delete(person);
}
public void flush() {
getCurrentSession().flush();
}
}
DomainRepository
package com.ssh.respository;
import java.io.Serializable;
import java.util.List;
public interface DomainRepository<T,PK extends Serializable>{
T load(PK id);
T get(PK id);
List<T> findAll();
void persist(T entity);
PK save(T entity);
void saveOrUpdate(T entity);
void delete(PK id);
void flush();
}
PersonRepository
package com.ssh.respository;
import com.ssh.entity.Person;
public interface PersonRepository extends DomainRepository<Person,Integer>
{
}
ServletInitializer
package com.ssh;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(SshApplication.class);
}
}
SshApplication
package com.ssh;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SshApplication {
public static void main(String[] args) {
SpringApplication.run(SshApplication.class, args);
}
}
具体代码是在网上参考一位网友的。
以下是一些资源网站大家下载jar包或者引入依赖时可以参考:
https://mvnrepository.com/artifact/org.hibernate/hibernate-c3p0/5.1.9.Final
https://docs.spring.io/spring-boot/docs/2.1.7.RELEASE/reference/htmlsingle/
http://repo.spring.io/release/org/springframework/spring/
https://www.mvnjar.com/org.hibernate/hibernate-c3p0/5.3.10.Final/detail.html
补充内容:在后来的工作中发现博文中的代码其实不算是一个血统纯正的springBoot整合hibernate
,只能是一个spring MVC的web工程,以下做一些代码上的修改以完善博文。
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!--<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>-->
</web-app>
web.xml中的内容都注释,不需要要添加,配置文件的内容由程序来加载,不需要由容器加载
springBoot启动类
SpringbootHibernateApplication
package com.springboothibernate;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource("classpath:config/applicationContext.xml")
public class SpringbootHibernateApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootHibernateApplication.class, args);
}
}
由@ImportResource(“classpath:config/applicationContext.xml”)去负责加载配置文件,其他内容不需要改变。
有网友说@ImportResource注解会使拦截器失效,我没有做过测试,如果有结论会另写博文做详细说明。