Spring Boot集成Hibernate

java技术文章

2018-11-09

44

0

一、这个事例使用到了如下技术:

  • Spring Boot 1.2.3 Release
  • Java1.7
  • Hibernate 4.3
  • Maven
  • Mysql

二、Spring Boot和Hibernate项目包结构

一个典型的项目包结构

三、项目依赖:

pox.xml

这里重要的事设置spring-boot-starter-data-jpa的依赖,它将引入所有内部的依赖包。

 
    4.0.0 
    org.springframework.samples 
    SpringBoot_Hibernate_Example 
    0.0.1-SNAPSHOT 
      
        1.7 
        UTF-8 
        UTF-8 
     
     
        org.springframework.boot 
        spring-boot-starter-parent 
        1.2.3.RELEASE 
         
     
     
         
            org.springframework.boot 
            spring-boot-starter-web 
         
         
            org.springframework.boot 
            spring-boot-starter-data-jpa 
         
         
            mysql 
            mysql-connector-java 
         
     
     
         
             
                org.springframework.boot 
                spring-boot-maven-plugin 
             
         
     

四、数据库Schema

在你的数据库中创建一个person表,因为我们将要从当前应用访问这张表(spring boot和hibernate集成)。

Database Table
CREATE TABLE person (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
pcity VARCHAR(255) NULL DEFAULT NULL,
name VARCHAR(255) NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)

五、创建person表对应的实体

Person.java
package com.onlinetutorialspoint.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "person")
public class Person {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    @Column(name = "pcity")
    private String city;

    public Person() {
        super();
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Person [pid=" + id + ", pName=" + name + ", pCity=" + city
                + "]";
    }

}

Person.java类作为Spring Boot Hibernate中的部分,并没有什么特别之处。它就是一个的简单hibernate application实体文件。

六、配置文件

配置信息连接数据库,并且它也由hibernate配置项组成,比如hibernate hbm2ddl auto.

配置文件:

application.properties
# Database
db.driver: com.mysql.jdbc.Driver
db.url: jdbc:mysql://localhost:3306/onlinetutorialspoint
db.username: root
db.password: 12345

# Hibernate
hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql: true
hibernate.hbm2ddl.auto: create
entitymanager.packagesToScan: com

七、创建一个DB配置文件

作为Spring boot Hibernate集成的一部分,这是一个主要的配置文件,主要用于创建数据源,Hibernate session Factory 和管理transactions.

DBConfiguration.java

package com.onlinetutorialspoint.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class DBConfiguration {
    @Value("${db.driver}")
    private String DRIVER;

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

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

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

    @Value("${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;

    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(DRIVER);
        dataSource.setUrl(URL);
        dataSource.setUsername(USERNAME);
        dataSource.setPassword(PASSWORD);
        return dataSource;
    }

    @Bean
    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;
    }

    @Bean
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory().getObject());
        return transactionManager;
    }
}

该DBConfiguration.java是一个配置文件,在Spring boot加载期间执行。

 @Configuration是一个注解,你讲在这里获得跟多的信息get more about @Configuration and @Bean here..

@EnableTransactionManagement它能启用注解驱动事务管理能力,我们也能通过使用<tx:*> XML命名空间启用。

@Value由spring famework提供。从Spring 3.0 版本开始.@Value注解用于表示驱动的依赖注入。一个通用情况是通过${db.driver}样式表达式设置默认值。

八、创建DAO类

一个PersionDAO.java类执行基础的增删改查操作。为了使Spring Boot Hibernate实例尽可能简单,我创建了一个从数据库读取所有个人信息的方法。

PersonDAO.java

package com.onlinetutorialspoint.dao;

import java.util.List;

import javax.transaction.Transactional;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.onlinetutorialspoint.model.Person;

@Repository
@Transactional
public class PersonDAO {
    @Autowired
    private SessionFactory sessionFactory;

    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    public String savePerson(Person person) {
        Long isSuccess = (Long)getSession().save(person);
        if(isSuccess >= 1){
            return "Success";
        }else{
            return "Error while Saving Person";
        }
        
    }

    public boolean delete(Person person) {
        getSession().delete(person);
        return true;
    }

    @SuppressWarnings("unchecked")
    public List getAllPersons() {
        return getSession().createQuery("from Person").list();
    }
}

九、创建Spring Controller :

PersonController.java

package com.onlinetutorialspoint.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.onlinetutorialspoint.dao.PersonDAO;
import com.onlinetutorialspoint.model.Person;

@Controller
@RequestMapping(value = "/person")
public class PersonController {
    @Autowired
    private PersonDAO personDao;

    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete(long id) {
        try {
            Person person = new Person();
            person.setId(id);
            personDao.delete(person);
        } catch (Exception ex) {
            return ex.getMessage();
        }
        return "Person succesfully deleted!";
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public String create(String name, String city) {
        try {
            Person person = new Person();
            person.setName(name);
            person.setCity(city);
            personDao.savePerson(person);
        } catch (Exception ex) {
            return ex.getMessage();
        }
        return "Person succesfully saved!";
    }
    @RequestMapping(value = "/allPersons")
    @ResponseBody
    public List getAllPersons() {
        try {
            return personDao.getAllPersons();
        } catch (Exception ex) {
            return null;
        }
    }
}

十、创建Spring Boot Application Class

Application.java

package com.onlinetutorialspoint;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

}

好了,我们已经创建完成Spring Boot Hibernate事例。现在只需要运行Aplication.java类,如果一切正常的话,你讲看到如下信息。

现在我们通过如下URL访问应用:http://localhost:8080/person/

十一、插入Person

http://localhost:8080/person/save?name=chandra shekhar Goka&city=Hiderabad

十二、显示所有Person

URL:http://localhost:8080/person/allPersons

欢迎访问:www.hongfu951.com博客,查看更多文章

发表评论

全部评论:0条

鸿福951

努力打造一个好用的webui

热评文章

推荐文章