Spring Data Jpa

1.pom.xml

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

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

		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper-spring-boot-starter</artifactId>
			<version>1.2.3</version>
		</dependency>

		<dependency>
			<groupId>org.mybatis.spring.boot</groupId>
			<artifactId>mybatis-spring-boot-starter</artifactId>
			<version>2.1.0</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

2.application.yml

server:
  port: 8080
  servlet:
    context-path: /
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false
    username: root
    password: alan
    type: com.zaxxer.hikari.HikariDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver      # 配置MySQL的驅動程序類
  jpa:
    database: MySQL
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    show-sql: true
    hibernate:
      ddl-auto: update


#ddl-auto
#create:每次運行程序時,都會重新創建表,故而數據會丟失
#create-drop:每次運行程序時會先創建表結構,然後待程序結束時清空表
#upadte:每次運行程序,沒有表時會創建表,如果對象發生改變會更新表結構,原有數據不會清空,只會更新#(推薦使用)
#validate:運行程序會校驗數據與數據庫的字段類型是否相同,字段不同會報錯
#none: 禁用DDL處理

3.Entity

package com.example.entity;

import java.util.Date;

import javax.persistence.*;

@Entity
@Table(name = "test_user")
public class User {

    @Id
//    @GenericGenerator(name = "idGenerator", strategy = "uuid")  //uuid策略
    @GeneratedValue(strategy = GenerationType.IDENTITY)        //自增
    private String id;

    @Column(name = "username", unique = true, nullable = false, length = 64)
    private String username;

    @Column(name = "email", length = 64)
    private String email;

    @Column(name = "create_time", nullable = false)
    private Date createTime;

	//get...set...

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", email=" + email + ", createTime=" + createTime + "]";
	}
    
}

4.dao

package com.example.dao;

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

import com.example.entity.User;

public interface UserRepository extends JpaRepository<User, String> {
    List<User> findByUsername(String username);
	
	List<User> findByUsernameLike(String username);
//自帶findAll,findById(String id),findAllById(ids)等
}

5.Controller

package com.example.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import com.example.dao.UserRepository;
import com.example.entity.User;

import java.util.Optional;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserRepository userRepository;


    @GetMapping("/{id}")
    public void deleteUser(@PathVariable("id") String userId) {
        userRepository.findById(userId);
    }

}

6.測試

package com.example;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.example.dao.UserRepository;

import java.util.Optional;

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserRepositoryTest {

    @Autowired
    private UserRepository userRepositoy;

    @Test
    public void findByIdTest() {
        Optional optional = userRepositoy.findById("1");
        System.out.println(optional.toString());
        Assert.assertNotNull(optional.get());
    }

    @Test
	public void findByUsernameTest() {
		List<User> optional = userRepositoy.findByUsername("2233");
		if (optional != null && optional.size() > 0) {
			for (User user : optional) {
				System.out.println(user.toString());
			}
		}
		List<User> optional1 = userRepositoy.findByUsernameLike("%" + "23" + "%");
		if (optional1 != null && optional1.size() > 0) {
			for (User user : optional1) {
				System.out.println(user.toString());
			}
		}
	}
}

7.測試結果

findByIdTest:

Hibernate: select user0_.id as id1_0_0_, user0_.create_time as create_t2_0_0_, user0_.email as email3_0_0_, user0_.username as username4_0_0_ from test_user user0_ where user0_.id=?
(sql語句打印)

Optional[User [id=1, username=2231, email=222, createTime=2019-10-25 09:00:50.0]]

(查詢結果打印)

findByUsernameTest:

Hibernate: select user0_.id as id1_0_, user0_.create_time as create_t2_0_, user0_.email as email3_0_, user0_.username as username4_0_ from test_user user0_ where user0_.username=?
User [id=2, username=2233, email=333, createTime=2019-10-25 23:04:29.0]
Hibernate: select user0_.id as id1_0_, user0_.create_time as create_t2_0_, user0_.email as email3_0_, user0_.username as username4_0_ from test_user user0_ where user0_.username like ?
User [id=1, username=2231, email=222, createTime=2019-10-25 09:00:50.0]
User [id=2, username=2233, email=333, createTime=2019-10-25 23:04:29.0]

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