springboot學習筆記(三):基於MySql數據庫的JPA操作

這裏主要介紹使用JPA方式的數據查詢操作

1 , 首先是pom.xml文件

這裏主要需要注意的是 , 使用JPA的依賴替換上一篇文章中的JDBC依賴
springboot學習筆記(二):基於MySql數據庫的JDBC操作

    <!-- MYSQL依賴 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
    <!-- JPA依賴 -->
    <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

2 , 下面是application.properties配置文件

###JPA配置
server.port=8011
spring.datasource.url = jdbc:mysql://localhost:3306/springbootdb
spring.datasource.username = root
spring.datasource.password = root
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. Default to "create-drop" when using an embedded database, "none" otherwise.
spring.jpa.hibernate.ddl-auto = update
# Hibernate 4 naming strategy fully qualified name. Not supported with Hibernate 5.
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

這裏配置了基本的數據庫連接信息和端口號

具體配置項可以參考官方文檔 : Common application properties

3 , UserInfo實體類

package com.springboot.JPA.entity;

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

/***
 * nickzhang 2016年9月2日
 */
@Entity
@Table(name = "tb_userinfo")
public class UserInfo implements Serializable{

    private static final long serialVersionUID = 2300044412175011558L;

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    @Column(name = "id", nullable = false)
    private int id;
    @Column(nullable = false , name = "name")
    private String name;
    @Column(nullable = false , name = "age")
    private String age;
    @Column(nullable = false , name = "address")
    private String address;


    public String getName() {
        return name;
    }

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

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getId() {
        return id;
    }

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

    @Override
    public String toString() {
        return "UserInfo{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

這裏需要注意的是

@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
private int id;

主鍵必須要有 , 否則啓動的時候會報如下錯誤

org.hibernate.AnnotationException: No identifier specified for entity

4 , Dao接口

package com.springboot.JPA.InterFace;

import com.springboot.JPA.entity.UserInfo;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;

import java.util.List;

/**
 * Created by nickzhang on 2016/9/2.
 */
public interface UserInfoDao extends CrudRepository<UserInfo,Integer>{

    @Query("select name,age,address from UserInfo")
    List<UserInfo> query();

}

5 , Service

package com.springboot.JPA.Service;

import com.springboot.JPA.InterFace.UserInfoDao;
import com.springboot.JPA.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by nickzhang on 2016/9/2.
 */
@Service
public class UserInfoService {

    @Autowired
    private UserInfoDao userInfoDao;

    public List<UserInfo> query(){
        return userInfoDao.query();
    }


}

6 , Controller

package com.springboot.JPA;

import com.springboot.JPA.Service.UserInfoService;
import com.springboot.JPA.entity.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by nickzhang on 2016/9/2.
 */
@SpringBootApplication
@RestController
public class SpringBootJPATest {

    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping("/query")
    public List<UserInfo> query(){
        return userInfoService.query();
    }

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

7 , 數據庫表

CREATE TABLE `tb_userinfo` (
  `name` varchar(255) NOT NULL,
  `age` varchar(255) NOT NULL,
  `address` varchar(255) NOT NULL,
  `id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

啓動main方法, 瀏覽器直接訪問

http://localhost:8011/query

返回結果爲

[
    [
        "張三",
        "27",
        "廣東深圳"
    ],
    [
        "李四",
        "25",
        "湖北武漢"
    ],
    [
        "王五",
        "29",
        "首都北京"
    ]
]

至此一個具有基本查詢功能的 , 基於JPA的springboot服務就完成了 .

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章