首页 > 代码库 > [五]SpringBoot 之 连接数据库(JPA-Hibernate)

[五]SpringBoot 之 连接数据库(JPA-Hibernate)

在具体介绍之前,先了解下什么是JPA

JPA全称JavaPersistence API.JPA通过JDK5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。

http://baike.baidu.com/link?url=LdqIXvzTr0RDjY2yoRdpogDdzaZ_L-DrIOpLLzK1z38quk6nf2ACoXEf3pWKTElHACS7vTawPTmoFv_QftgT_q

下面具体介绍怎么配置

第一种方式(最简单最快速的实现连接 推荐使用第二种)

1.引入jar包

pom.xml配置:

<dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

2.配置application.properties

关于application.properties

springboot中允许修改默认的配置,一般在resource文件下添加application.properties文件,修改相关的配置

########################################################
###datasource
########################################################

spring.datasource.url = jdbc:mysql://123.206.228.200:3306/test

spring.datasource.username = shijunjie

spring.datasource.password = *******

spring.datasource.driverClassName = com.mysql.jdbc.Driver

spring.datasource.max-active=20

spring.datasource.max-idle=8

spring.datasource.min-idle=8

spring.datasource.initial-size=10

########################################################

### Java Persistence Api

########################################################

# Specify the DBMS

spring.jpa.database = MYSQL

# Show or not log for each sql query

spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update)

spring.jpa.hibernate.ddl-auto = create-drop

# Naming strategy

#[org.hibernate.cfg.ImprovedNamingStrategy #org.hibernate.cfg.DefaultNamingStrategy]

spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy

# stripped before adding them to the entity manager)

spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5Dialect

3.编写实体类

package me.shijunjie.entity;

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

@Entity //加入这个注解,Demo就会进行持久化了
@Table(name="t_demo")
public class Demo {
    
    public Demo() {
    }

    public Demo(long id, String name) {
        this.id = id;
        this.name = name;
    }

    @Id
    @GeneratedValue
    private long id;

    @Column(name="tname")
    private String name;

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

4.编写DAO

package me.shijunjie.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import me.shijunjie.entity.Demo;

public interface DemoDao extends JpaRepository<Demo, Long> {

}

5.编写Service接口及其实现类

接口:

package me.shijunjie.service;

import me.shijunjie.entity.Demo;

public interface DemoService {
    public void save(Demo demo);
}

实现类:

package me.shijunjie.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.shijunjie.dao.DemoDao;
import me.shijunjie.entity.Demo;
import me.shijunjie.service.DemoService;

@Service
public class DemoServiceImpl implements DemoService {

    @Autowired
    private DemoDao demoDao;

    public void save(Demo demo){
        demoDao.save(demo);
    }
}

6.编写Controller

package me.shijunjie.controller;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import me.shijunjie.entity.Demo;
import me.shijunjie.service.DemoService;

@RestController
@RequestMapping("/demo")
public class DemoController {

    @Resource
    private DemoService demoService;


    /**

     * 测试保存数据方法.

     * @return

     */

    @RequestMapping("/save")
    public String save(){
        Demo d = new Demo();
        d.setName("Angel");
        demoService.save(d);//保存数据.
        return "ok.DemoController.save";

    }
}

7.编写入口

package me.shijunjie.controller;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.boot.orm.jpa.EntityScan;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;

@ComponentScan(basePackages={"me.shijunjie"}) // 扫描该包路径下的所有spring组件
@EnableJpaRepositories("me.shijunjie.dao") // JPA扫描该包路径下的Repositorie
@EntityScan("me.shijunjie.entity") // 扫描实体类
@SpringBootApplication
@EnableScheduling
public class App extends SpringBootServletInitializer{
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

输入spring-boot:run进行测试

打开浏览器输入http://localhost:8080/demo/save

技术分享

查看数据库表中是否存入了数据

技术分享

运行成功!

 

第二种方式(推荐)

参照http://blog.csdn.net/u012373815/article/details/53240946

[五]SpringBoot 之 连接数据库(JPA-Hibernate)