spring+hibernate

 

pom.xml

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.1.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.12.Final</version>
        </dependency>

        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.8-dmr</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.13</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>
    </dependencies>
View Code

BaseDao

package org.mythsky.springtransaction;

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

public interface BaseDao<T> {
    T get(Class<T> entityClazz, Serializable id);
    Serializable save(T entity);
    void update(T entity);
    void delete(T entity);
    void delete(Class<T> entityClazz,Serializable id);
    List<T> findAll(Class<T> entityClazz);
    long findCount(Class<T> entityClazz);
}
View Code

BaseDaoHibernate5

package org.mythsky.springtransaction;

import org.hibernate.SessionFactory;
import org.hibernate.query.Query;

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

public class BaseDaoHibernate5<T> implements BaseDao<T> {
    private SessionFactory sessionFactory;

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    /**
     * 根据ID加载实体
     * @param entityClazz
     * @param id
     * @return
     */
    public T get(Class<T> entityClazz, Serializable id) {
        return (T)getSessionFactory().getCurrentSession().get(entityClazz,id);
    }

    /**
     * 保存实体
     * @param entity
     * @return
     */
    public Serializable save(T entity) {
        return getSessionFactory().getCurrentSession().save(entity);
    }

    /**
     * 更新实体
     * @param entity
     */
    public void update(T entity) {
        getSessionFactory().getCurrentSession().saveOrUpdate(entity);
    }

    /**
     * 删除实体
     * @param entity
     */
    public void delete(T entity) {
        getSessionFactory().getCurrentSession().delete(entity);
    }

    /**
     * 根据ID删除实体
     * @param entityClazz
     * @param id
     */
    public void delete(Class<T> entityClazz,Serializable id) {
        getSessionFactory().getCurrentSession()
                .createQuery("delete "+entityClazz.getSimpleName()+" en where en.id=?0")
                .setParameter("0",id)
                .executeUpdate();
    }

    /**
     * 获取所有实体
     * @param entityClazz
     * @return
     */
    public List<T> findAll(Class<T> entityClazz) {
        return find("select * from "+entityClazz.getSimpleName()+" en");
    }

    /**
     * 获取实体总数
     * @param entityClazz
     * @return
     */
    public long findCount(Class<T> entityClazz) {
        List<?> list=find("select count(1) from "+entityClazz.getSimpleName());
        if(list!=null&&list.size()==1){
            return (Long)list.get(0);
        }
        return 0;
    }

    /**
     * 根据HQL语句查询实体
     * @param sql
     * @return
     */
    protected List<T> find(String sql){
        return (List<T>)getSessionFactory().getCurrentSession().createQuery(sql).list();
    }

    /**
     * 根据带占位符参数的HQL语句查询实体
     * @param sql
     * @param params
     * @return
     */
    protected List<T> find(String sql,Object...params){
        Query query= getSessionFactory().getCurrentSession().createQuery(sql);
        for(int i=0,len=params.length;i<len;i++){
            query.setParameter(i+"",params[i]);
        }
        return (List<T>)query.list();
    }

    /**
     * 使用HQL语句进行分页查询操作
     * @param sql
     * @param pageNo
     * @param pagesize
     * @return
     */
    protected List<T> findByPage(String sql,int pageNo,int pagesize){
        return getSessionFactory().getCurrentSession().createQuery(sql)
                .setFirstResult((pageNo-1)*pagesize)
                .setMaxResults(pagesize)
                .list();
    }

    /**
     * 使用HQL语句进行分页查询操作
     * @param sql
     * @param pageNo
     * @param pagesize
     * @param params
     * @return
     */
    protected List<T> findByPage(String sql,int pageNo,int pagesize,Object...params){
        Query query=getSessionFactory().getCurrentSession().createQuery(sql);
        for(int i=0;i<params.length;i++){
            query.setParameter(i+"",params[i]);
        }
        return query.setFirstResult((pageNo-1)*pagesize)
                .setMaxResults(pagesize)
                .list();
    }
}
View Code

Book

package org.mythsky.springtransaction;

import javax.persistence.*;

@Entity
@Table(name="book_inf")
public class Book
{
    @Id @Column(name="book_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;
    @Column(name="book_name")
    private String name;
    private double price;
    private String author;
    public Integer getId()
    {
        return id;
    }
    public void setId(Integer id)
    {
        this.id = id;
    }
    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public double getPrice()
    {
        return price;
    }
    public void setPrice(double price)
    {
        this.price = price;
    }
    public String getAuthor()
    {
        return author;
    }
    public void setAuthor(String author)
    {
        this.author = author;
    }
}
View Code

BookDao

package org.mythsky.springtransaction;

import java.util.List;

public interface BookDao extends BaseDao<Book>
{
}
View Code

BookDaoHibernate5

package org.mythsky.springtransaction;

public class BookDaoHibernate5 extends BaseDaoHibernate5<Book> implements BookDao {
}
View Code

BookService

package org.mythsky.springtransaction;

public interface BookService {
    int addBook(Book book);
}
View Code

BookServiceImpl

package org.mythsky.springtransaction;

public class BookServiceImpl implements BookService {
    private BookDao bookDao;

    public void setBookDao(BookDao bookDao) {
        this.bookDao = bookDao;
    }

    public int addBook(Book book) {
        return (Integer)bookDao.save(book);
    }
}
View Code

BookController

package org.mythsky.springtransaction;

public class BookController {
    private BookService bookService;

    public void setBookService(BookService bookService) {
        this.bookService = bookService;
    }

    private Book book;

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    public void add(){
        int result=bookService.addBook(book);
        if(result>0){
            System.out.println("图书添加成功!");
        }else{
            System.out.println("图书添加失败!");
        }
    }
}
View Code

SpringTest

package org.mythsky.springtransaction;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {
    public static void main(String[] args){
        ApplicationContext ctx=new ClassPathXmlApplicationContext("services.xml");
        Book book=new Book();
        book.setName("Hello");
        book.setAuthor("World");
        book.setPrice(25);
        BookService service=ctx.getBean("bookService",BookService.class);
        int result= service.addBook(book);
        if(result>0){
            System.out.println("图书添加成功!");
        }else{
            System.out.println("图书添加失败!");
        }
    }
}
View Code

services.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:p="http://www.springframework.org/schema/p"
       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 ">

    <!--<bean id="steelAxe" class="org.mythsky.springdemo.SteelAxe"></bean>-->
    <!--<bean id="chinese" class="org.mythsky.springdemo.Chinese" init-method="init" p:axe-ref="steelAxe" p:name="依赖注入的值"></bean>-->
    <!--<bean class="org.mythsky.springdemo.MyBeanPostProcessor"></bean>-->
    <!--<bean class="org.mythsky.springdemo.MyBeanFactoryPostProcessor"></bean>-->
    <!--<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">-->
        <!--<property name="locations">-->
            <!--<list>-->
                <!--<value>dbconn.properties</value>-->
            <!--</list>-->
        <!--</property>-->
    <!--</bean>-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
          p:driverClass="${jdbc.driverClassName}"
          p:jdbcUrl="${jdbc.url}"
          p:user="${jdbc.username}"
          p:password="${jdbc.password}"></bean>
    <!--<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"-->
    <!--p:dataSource-ref="dataSource"></bean>-->
    <!--<bean id="newsDao" class="org.mythsky.springtransaction.NewsDaoImpl"-->
          <!--p:ds-ref="dataSource"></bean>-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT" propagation="REQUIRED" timeout="5"></tx:method>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="myPointcut" expression="bean(bookService)"></aop:pointcut>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut"></aop:advisor>
    </aop:config>
    <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"
          p:dataSource-ref="dataSource">
        <property name="annotatedClasses">
            <list>
                <value>org.mythsky.springtransaction.Book</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
    </bean>
    <bean id="bookDao" class="org.mythsky.springtransaction.BookDaoHibernate5"
          p:sessionFactory-ref="sessionFactory"></bean>
    <bean id="bookService" class="org.mythsky.springtransaction.BookServiceImpl"
          p:bookDao-ref="bookDao"></bean>
    <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager"
          p:sessionFactory-ref="sessionFactory"></bean>
    <!--<bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">-->
        <!--<property name="locations">-->
            <!--<list>-->
                <!--<value>db.properties</value>-->
            <!--</list>-->
        <!--</property>-->
    <!--</bean>-->
    <!--<bean id="dataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"></bean>-->
    <context:property-placeholder location="dbconn.properties"></context:property-placeholder>
    <!--<context:property-override location="db.properties"></context:property-override>-->
    <context:component-scan base-package="org.mythsky.springtransaction"></context:component-scan>
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    <!--<bean id="myAspect" class="org.mythsky.springaopdemo.AuthAspect"></bean>-->
    <!--<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"></bean>-->
</beans>
View Code

注意使用hibernate需要配置事务,否则会报错

运行SprintTest

查看数据库

 

posted @ 2017-12-05 17:59  uptothesky  阅读(161)  评论(0编辑  收藏  举报