1.DoMain.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; /**
* 测试Spring Boot Data Jpa
*
*/
@SpringBootApplication //等同于 @Configuration @EnableAutoConfiguration @ComponentScan
public class DoMain
{
public static void main( String[] args )
{
SpringApplication.run(DoMain.class, args);
}
}

2.User.java

import java.sql.Date;
import java.util.List; import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; /**
* 用户实体类
*
*/
@Component
//@ConfigurationProperties(prefix="my",locations = "classpath:application.yml")
@ConfigurationProperties(prefix="my") //配合测试类@SpringBootTest()使用
@Entity
//@NamedQueries({
//@NamedQuery(name = "User.findByNameWithNamedQuery",
//query = "select c from User c where c.name = ?1")})
public class User {
@Id
private int id;
private String name;
private char sex;
private Date birthDate;
private int height;
@OneToMany(mappedBy="myUser",fetch=FetchType.EAGER)
private List<ContactBook> contact; public User(){} public User(int id ,String name,char sex,Date birthDate,int height,List<ContactBook> contact){
this.id = id;
this.name = name;
this.sex = sex;
this.birthDate = birthDate;
this.height = height;
this.contact = contact;
} public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public List<ContactBook> getContact() {
return contact;
}
public void setContact(List<ContactBook> contact) {
this.contact = contact;
}
public void setName(String name) {
this.name = name;
}
public char getSex() {
return sex;
}
public void setSex(char sex) {
this.sex = sex;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
} }

3.ContackBook.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; /**
* 通讯信息实体类
*
*/
@Entity
@Component
public class ContactBook {
@Id
private int id;
// @Column(name = "userId",nullable=false)
private int userId;
private int type;
private String contact; @ManyToOne
private User myUser; public ContactBook(){} public ContactBook(int id,int userId,int type,String contact){
this.id = id;
this.userId = userId;
this.type = type;
this.contact = contact;
} public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
} }

4.UserRepository.java

import java.util.List;

import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param; import com.maven.demo.model.User; public interface UserRepository extends JpaRepository<User, Integer>{
//基于方法名的查询
public User readByName(String name); //基于方法名的查询,可分页的模糊查询
public List<User> findAllByNameLike(String name,Pageable pageable); /**
* @Modifying表明@Query是更新或删除语句
*/
@Modifying(clearAutomatically = true)
@Query("update User c set c.name=:newName where c.name like :qname")
public int updateAllByNameLike(@Param("qname") String name, @Param("newName") String newName); /**
* 使用了原生SQL,由于命名的原因,这里的原生SQL和JPQL看上去差别不大
*/
@Modifying(clearAutomatically = true)
@Query(value = "delete from User c where c.name like :qname",nativeQuery = true)
public int deleteAllByNameLike(@Param("qname") String name);
}

5.ContackBookRepository.java

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

import com.maven.demo.model.ContactBook;

public interface ContactBookRepository extends JpaRepository<ContactBook, Integer>{

}

6.BootDataTest.java(测试类)

import static org.junit.Assert.*;

import java.sql.Date;
import java.util.ArrayList;
import java.util.List; import org.junit.Before;
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.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional; import com.maven.demo.interfaces.ContactBookRepository;
import com.maven.demo.interfaces.UserRepository;
import com.maven.demo.model.ContactBook;
import com.maven.demo.model.User; @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class BootDataTest {
@Autowired
private UserRepository userDao; @Autowired
private ContactBookRepository bookDao; @Before
public void testInit() {
List<ContactBook> books = new ArrayList<ContactBook>();
ContactBook book = new ContactBook(1,2421,1,"123");
books.add(book);
bookDao.save(book); User user = new User(2421, "天恒",'男',new Date(1),168,books);
userDao.save(user); // for(int i = 0;i < 20;i++){
// User user = new User(2420 + i, "天恒" + i,'男',new Date(1),168,books);
// userDao.save(user);
// }
} @Test
@Transactional //需要添加事务,否则user获取不了里面List<ContactBook>的信息
public void testFindContactBookByUser(){
User user = userDao.readByName("天恒"); assertEquals(1, user.getContact().size());
} @Test
public void testfindAllByNameLike(){
// 排序条件,降序,
Sort sort = new Sort(Direction.DESC, new String[] { "name", "id" }); // 分页条件,第一页,每页10条
Pageable pagination = new PageRequest(0, 10, sort); List<User> list = userDao.findAllByNameLike("%天%",pagination);
assertEquals(1,list.size());
} @Test
@Transactional //需要添加这个注解才能更新
public void testUpdateAllByNameLike(){
userDao.updateAllByNameLike("%天恒%", "竹清");
User user = userDao.findOne(2421);
assertEquals("竹清", user.getName());
} @Test
@Transactional
public void testDeleteAllByNameLike(){
userDao.deleteAllByNameLike("%天恒%");
User user = userDao.findOne(2421);
assertNull(user);
} }

7.pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.maven</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>demo</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source> <!-- Java版本,不要在build path里面修改 -->
<maven.compiler.target>1.8</maven.compiler.target>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.5</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.7.RELEASE</version>
</dependency> <dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.9</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>1.4.0.RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<version>1.4.0.RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<version>1.4.0.RELEASE</version>
<optional>true</optional>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>1.4.0.RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>1.4.0.RELEASE</version>
</dependency> <dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.192</version>
</dependency> </dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>

另附:pom.xml(使用parent标签的配置方法)(推荐)

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent> <groupId>demo</groupId>
<artifactId>huawei</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>huawei</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source> <!-- Java版本 -->
<maven.compiler.target>1.8</maven.compiler.target>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency> <dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<!-- 使用mysql作为数据库,这里已经使用了H2-->
<!--
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
-->
<!-- 连接池 -->
<!-- Spring Boot默认使用Tomcat连接池 -->
<!-- 也可以通过配置使用其他连接池 -->
<!--
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<scope>compile</scope>
</dependency>
-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> </project>

Spring------Spring boot data jpa的使用方法的更多相关文章

  1. Spring boot data JPA数据库映射关系 : @OneToOne,@OneToMany,@ManyToMany

    问题描述 在利用Spring boot data JPA进行表设计的时候,表对象之间经常存在各种映射关系,如何正确将理解的映射关系转化为代码中的映射关系是关键之处. 解决办法 概念理解 举例:在公司的 ...

  2. Spring Data JPA 梳理 - 使用方法

    1.下载需要的包. 需要先 下载Spring Data JPA 的发布包(需要同时下载 Spring Data Commons 和 Spring Data JPA 两个发布包,Commons 是 Sp ...

  3. Spring boot data jpa 示例

    一.maven pom.xml文件 <?xml version="1.0" encoding="UTF-8"?> <project xmlns ...

  4. Spring Data JPA 简单查询--方法定义规则

    一.常用规则速查 1  And 并且2  Or  或3  Is,Equals 等于4  Between  两者之间5  LessThan 小于6  LessThanEqual   小于等于7  Gre ...

  5. 扩展spring data jpa的数据更新方法时注意事项

    //此处必须加@Transactional,否则不能运行,报错 @Transactional @Modifying @Query("update ExamItem a set a.versi ...

  6. 74. Spring Data JPA方法定义规范【从零开始学Spring Boot】

    [从零开始学习Spirng Boot-常见异常汇总] 事情的起因:有人问过我们这个这个问题:为什么我利用Spring data jpa写的方法没有按照我想要的情况进行执行呢?我记得当时只是告诉他你你先 ...

  7. spring boot系列(五)spring boot 配置spring data jpa (查询方法)

    接着上面spring boot系列(四)spring boot 配置spring data jpa 保存修改方法继续做查询的测试: 1 创建UserInfo实体类,代码和https://www.cnb ...

  8. Spring Data JPA简单使用

    用Spring Data JPA操作数据库 这份教程教你用Spring Data JPA从关系数据库mysql中存储和提取数据.总结来自https://spring.io/guides/gs/acce ...

  9. SpringBoot学习笔记:Spring Data Jpa的使用

    更多请关注公众号 Spring Data Jpa 简介 JPA JPA(Java Persistence API)意即Java持久化API,是Sun官方在JDK5.0后提出的Java持久化规范(JSR ...

随机推荐

  1. centos 手动编译 fcitx 各种问题大全

    yum install ncurses-devel   tinyxml-devel sqlite-devel wget http://downloads.sourceforge.net/project ...

  2. Objective-C的“多继承”——消息转发

    Objective-C的“多继承”——消息转发 当单继承不够用,很难为问题域建模时,我们通常都会直接想到多继承.多继承是从多余一个直接基类派生类的能力,可以更加直接地为应用程序建模.但是Objecti ...

  3. mysql 匹配 findinset

     SELECT FS_ITEM_DESC FROM dictionary  WHERE FS_TYPE = 'prizeType' AND FIND_IN_SET(FS_ITEM_CODE,(SELE ...

  4. shadowshocks下载地址

    https://github.com/shadowsocks/shadowsocks-windows/releases

  5. CSS3和js炫酷点击按钮3D翻转动画特效

    简要教程 flipside是一款使用CSS3和js制作的炫酷点击按钮无缝过渡到确认面板的过渡动画特效.该点击按钮特效在按钮不同方向的边部点击时,产生的过渡动画特效是不一样的. 在线预览   源码下载 ...

  6. jQuery (二)DOM 操作

    一般jquery在web项目的只要作用就是取值和赋值了. 下面了入门下,这些值得获取. <!DOCTYPE html> <html> <head> <meta ...

  7. linqtosql 实现数据分页

    cs代码 using System; using System.Collections.Generic; using System.Linq; using System.Web; using Syst ...

  8. jQuery 选择器大全总结

    jQuery基础语法中规定的选择器有三种,分别是类选择器.ID选择器.标签选择器.如:$(“.aa”).$(“#id”).$(“div”),但中实际的应用中,DOM机构非常复杂,层级非常多.如和应对这 ...

  9. linux网口驱动实现(待续)

    驱动位于linux/driver/net下. 1. 寄存器读写 asm/io.h #define __raw_writeb(v,a)   (__chk_io_ptr(a), *(volatile un ...

  10. 检查 Linux 服务器性能

    如何用十条命令在一分钟内检查 Linux 服务器性能 如果你的Linux服务器突然负载暴增,报警短信快发爆你的手机,如何在最短时间内找出Linux性能问题所在?来看Netflix性能工程团队的这篇博文 ...