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>