美文网首页
深入学习java笔记-3.Spring整合Hibernate(注

深入学习java笔记-3.Spring整合Hibernate(注

作者: 笨鸡 | 来源:发表于2019-04-30 15:18 被阅读0次

1.工程目录图

Spring_hibernate_annotation.png

2.配置文件

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>SSH</groupId>
    <artifactId>com.ctgu</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.6.RELEASE</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.2.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-entitymanager -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>5.4.2.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-ehcache -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-ehcache</artifactId>
            <version>5.4.2.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
        <dependency>
            <groupId>net.sf.ehcache</groupId>
            <artifactId>ehcache</artifactId>
            <version>2.10.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.6</version>
            <scope>provided</scope>
        </dependency>


        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.26</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.26</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
        <!--<dependency>-->
        <!--<groupId>commons-logging</groupId>-->
        <!--<artifactId>commons-logging</artifactId>-->
        <!--<version>1.2</version>-->
        <!--</dependency>-->
        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
        <!--<dependency>-->
            <!--<groupId>org.junit.jupiter</groupId>-->
            <!--<artifactId>junit-jupiter-api</artifactId>-->
            <!--<version>RELEASE</version>-->
            <!--<scope>compile</scope>-->
        <!--</dependency>-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>

    </dependencies>
</project>
db.properties
#mysql database setting
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&characterEncoding=utf8&useSSL=false
jdbc.user=root
jdbc.password="password"
jdbc.checkoutTimeout=30000
jdbc.idleConnectionTestPeriod=60
jdbc.maxIdleTime=30
jdbc.initialPoolSize=5
jdbc.minPoolSize=5
jdbc.maxPoolSize=40
jdbc.acquireIncrement=5 

#hibernate config
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=update
hibernate.current_session_context_class=thread
hibernate.cache.use_second_level_cache = false
hibernate.cache.use_query_cache=false
hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.cache.provider_configuration_file_resource_path=ehcache.xml
log4j.properties
### set log levels ###  INFO
log4j.rootLogger = INFO,stdout,E

log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern =  %d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.logger.org.quartz=INFO 
log4j.appender.E= org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =logs/mylogs.log
log4j.appender.E.DatePattern=yyyy-MM-dd'.log'
log4j.appender.E.Threshold =INFO
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern =%-d{yyyy-MM-dd HH\:mm\:ss}[%c] [%t\:%r] - [%p]  %m%n

#为了显示参数
log4j.logger.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
log4j.loggerorg.hibernate.type.descriptor.sql.BasicExtractor=TRACE

#查看查询中命名参数的值
log4j.logger.org.hibernate.engine.QueryParameters=DEBUG
log4j.logger.org.hibernate.engine.query.HQLQueryPlan=DEBUG
bean.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: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/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd
">

    <!--<context:annotation-config/>-->

    <context:component-scan base-package="com.ctgu.ssh"/>

    <aop:aspectj-autoproxy/>

    <context:property-placeholder location="db.properties"/>

    <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
        <property name="driverClass" value="${jdbc.driverClass}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="checkoutTimeout" value="${jdbc.checkoutTimeout}" />
        <!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
        <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}" />
        <!-- 连接数据库连接池最大空闲时间 -->
        <property name="maxIdleTime" value="${jdbc.maxIdleTime}" />
        <!-- 连接池初始化连接数 -->
        <property name="initialPoolSize" value="${jdbc.initialPoolSize}" />
        <property name="minPoolSize" value="${jdbc.minPoolSize}" />
        <property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
        <property name="acquireIncrement" value="${jdbc.acquireIncrement}" />

    </bean>

    <bean id="localSessionFactoryBean" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="comboPooledDataSource"/>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <!-- <prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop> -->
                <!-- 开启二级缓存 ehcache -->
                <!--<prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>-->
                <!--<prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>-->
                <!--<prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>-->
                <!--<prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}</prop>-->
            </props>
        </property>
        <property name="packagesToScan" value="com.ctgu.ssh"/>
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="localSessionFactoryBean"/>
        <property name="dataSource" ref="comboPooledDataSource"/>
    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" />

</beans>

3.Java类

Student.java
package com.ctgu.ssh.pojo;


import lombok.*;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;


@Data
@Entity
@DynamicInsert
@DynamicUpdate
@NoArgsConstructor
@Table(name="t_student")
public class Student implements Serializable {

    private static final long serialVersionUID = 8021925565032055905L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column
    @NonNull
    private String name;

    @Column
    private Date date;

}
IStudentDao.java
package com.ctgu.ssh.dao;

import com.ctgu.ssh.pojo.Student;

import java.util.List;

public interface IStudentDao {
    int addStudent(Student student);
    Student findStudentById(int id);
    List<Student> findAllStudent();
    List<Student> findAllStudentBySQL();
    void updateStudentNameById(String name, int id);
}
StudentDaoImpl.java
package com.ctgu.ssh.dao;

import com.ctgu.ssh.pojo.Student;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.io.Serializable;
import java.util.List;

@Repository
public class StudentDaoImpl implements IStudentDao {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public int addStudent(Student student) {
        Serializable count = sessionFactory.getCurrentSession().save(student);
        return (Integer) count;
    }

    @Override
    public Student findStudentById(int id) {
        Student student = sessionFactory.getCurrentSession().get(Student.class, id);
        return student;
    }

    @Override
    @SuppressWarnings("all")
    public List<Student> findAllStudent() {
        Session session = sessionFactory.openSession();
        List<Student> studentList = (List<Student>) session.createQuery("from Student").list();
//        List<Student> studentList = (List<Student>) session.createSQLQuery("select * from t_student").list();
        session.close();
        return studentList;
    }

    @Override
    public List<Student> findAllStudentBySQL() {
        Session session = sessionFactory.openSession();
        List<Student> studentList = session.createSQLQuery("select * from t_student where name = 'CT'")
                .addEntity(Student.class).list();
        session.close();
        return studentList;
    }

    @Override
    public void updateStudentNameById(String name, int id) {
        Student student = sessionFactory.getCurrentSession().get(Student.class, id);
        student.setName(name);
    }
}
IStudentService.java
package com.ctgu.ssh.service;

import com.ctgu.ssh.pojo.Student;

import java.util.List;

public interface IStudentService {
    int addStudent(Student student);
    Student findStudentById(int id);
    List<Student> findAllStudent();
    List<Student> findAllStudentBySQL();
    void updateStudentNameById(String name, int id);
}
StudentServiceImpl.java
package com.ctgu.ssh.service;

import com.ctgu.ssh.dao.IStudentDao;
import com.ctgu.ssh.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class StudentServiceImpl implements IStudentService {

    @Autowired
    private IStudentDao dao;

    @Override
    @Transactional
    public int addStudent(Student student) {
        int result = dao.addStudent(student);
        return result;
    }

    @Override
    @Transactional
    public Student findStudentById(int id) {
        Student student = dao.findStudentById(id);
        return student;
    }

    @Override
    @Transactional
    public List<Student> findAllStudent() {
        List<Student> studentList = dao.findAllStudent();
        return studentList;
    }

    @Override
    @Transactional
    public List<Student> findAllStudentBySQL() {
        List<Student> studentList = dao.findAllStudentBySQL();
        System.out.println(studentList);
        return studentList;
    }

    @Override
    @Transactional
    public void updateStudentNameById(String name, int id) {
        dao.updateStudentNameById(name, id);
    }
}
MyTest.java
package com.ctgu.ssh;

import com.ctgu.ssh.pojo.Student;
import com.ctgu.ssh.service.IStudentService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.Date;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:bean.xml"})
public class MyTest {
    @Autowired
    public IStudentService service;

    @Test
    public void testInsert() {
        Student student = new Student();
        student.setDate(new Date());
        student.setName("CT");
        service.addStudent(student);
    }

    @Test
    public void testFindStudentById() {
        Student student = service.findStudentById(3);
        System.out.println(student);
    }

    @Test
    public void testFindAllStudent() {
        List<Student> studentList = service.findAllStudent();
        System.out.println(studentList);
    }

    @Test
    public void testFindAllStudentBySQL() {
        List<Student> studentList = service.findAllStudentBySQL();
        System.out.println(studentList.get(0).getName());
    }

    @Test
    public void testUpdateStudentNameById(){
        service.updateStudentNameById("ct", 5);
    }

}

相关文章

网友评论

      本文标题:深入学习java笔记-3.Spring整合Hibernate(注

      本文链接:https://www.haomeiwen.com/subject/fnlvnqtx.html