SpringBoot之路程序员spring boot 相关

SpringBoot整合Hibernate

2018-06-07  本文已影响9人  垃圾简书_吃枣药丸
  1. 依赖
        <!--jpa-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.21</version>
        </dependency>
         <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.19</version>
        </dependency>
  1. 入口类
@SpringBootApplication
public class TemplateApplication {

    public static void main(String[] args) {
        SpringApplication.run(TemplateApplication.class, args);
    }
}
  1. application.yml
# mysql
  datasource:
    url: jdbc:mysql://localhost:3306/springBoot?useUnicode=true&amp;characterEncoding=UTF-8
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

  jpa:
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL5Dialect

hibernate:
  dialect: org.hibernate.dialect.MySQL5Dialect
  show_sql: true
  hbm2ddl:
    auto: update
entitymanager:
  packagesToScan: com.futao.entity
  1. 新建HibernateConfiguration.java配置类
package com.futao;

import com.alibaba.druid.pool.DruidDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

import org.springframework.orm.hibernate5.HibernateTransactionManager;

import java.util.Properties;

/**
 * @author futao
 * Created on 18-6-7-下午5:26.
 */
@Configuration
@EnableTransactionManagement
public class HibernateConfiguration {
    @Value("${spring.datasource.driver-class-name}")
    private String DRIVER;

    @Value("${spring.datasource.password}")
    private String PASSWORD;

    @Value("${spring.datasource.url}")
    private String URL;

    @Value("${spring.datasource.username}")
    private String USERNAME;

    @Value("${spring.jpa.properties.hibernate.dialect}")
    private String DIALECT;

    @Value("${hibernate.show_sql}")
    private String SHOW_SQL;

    @Value("${hibernate.hbm2ddl.auto}")
    private String HBM2DDL_AUTO;

    @Value("${entitymanager.packagesToScan}")
    private String PACKAGES_TO_SCAN;

    /**
     * @return
     */
    @Bean(value = "sessionFactory")
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(PACKAGES_TO_SCAN);
        Properties hibernateProperties = new Properties();
        hibernateProperties.put("hibernate.dialect", DIALECT);
        hibernateProperties.put("hibernate.show_sql", SHOW_SQL);
        hibernateProperties.put("hibernate.hbm2ddl.auto", HBM2DDL_AUTO);
        sessionFactory.setHibernateProperties(hibernateProperties);

        return sessionFactory;
    }

    /**
     * @return
     */
    @Bean
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(DRIVER);
        dataSource.setUrl(URL);
        dataSource.setUsername(USERNAME);
        dataSource.setPassword(PASSWORD);
        dataSource.setInitialSize(10);
        dataSource.setMinIdle(10);
        dataSource.setMaxActive(100);
        return dataSource;
    }
}
  1. service

package com.futao.service;

import com.futao.entity.User;
import com.futao.mapper.UserMapper;
import face.com.futao.service.IUserService;
import org.apache.ibatis.annotations.Result;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;

/**
 * @author futao
 * Created on 18-6-7-上午11:29.
 */
@Transactional
@Service
public class UserService implements IUserService {

    @Autowired
    @Qualifier("sessionFactory")
    private SessionFactory sessionFactory;

    /**
     * 添加用户
     *
     * @param user
     * @return
     */
    @Override
    public int add(User user) {
         sessionFactory.getCurrentSession().save(user);
        return 1;
    }

    public List<User> list() {
        List list = sessionFactory.getCurrentSession().createCriteria(User.class)
                                  .add(Restrictions.ge("age", 10))
                                  .list();
        return (List<User>) list;
    }
}

OJBK
源码:https://gitee.com/FutaoSmile/springboot

参考:Spring Boot Hibernate example
参考:Spring Boot + Hibernate 5 + Mysql Example
Bing国际版:https://cn.bing.com/?ensearch=1&FORM=BEHPTB

上一篇下一篇

猜你喜欢

热点阅读