一、引入依赖
<!--Spring Data JPA依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--数据库驱动,这里使用sqlServer-->
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
</dependency>
二、配置文件
spring:
datasource:
url: ""
username: ""
password: ""
driver-class-name: ""
jpa:
hibernate:
ddl-auto: update
show-sql: true
三、使用
-
实体类
package com.example.jpademo.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.Proxy; /** * knowledge * @author */ @Table(name="knowledge") @Data @Entity @NoArgsConstructor @AllArgsConstructor public class Knowledge implements Serializable { /** * 条目编号 */ @Id @GeneratedValue(generator = "JDBC",strategy = GenerationType.IDENTITY) private Integer id; /** * 标题 */ private String title; /** * 最后更改时间 */ private Date lastmodified; /** * 内容 */ private String content; /** * 类别编号 */ private Integer classid; private static final long serialVersionUID = 1L; @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", title=").append(title); sb.append(", lastmodified=").append(lastmodified); sb.append(", content=").append(content); sb.append(", classid=").append(classid); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
-
DAO
package com.example.jpademo.dao; import com.example.jpademo.entity.Knowledge; import org.springframework.data.domain.Page; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaSpecificationExecutor; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; import javax.persistence.Column; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import java.util.List; public interface KnowledgeDao extends JpaRepository<Knowledge,Integer>,JpaSpecificationExecutor<Knowledge>{ //id>= min AND id<=max List<Knowledge> findByIdGreaterThanAndIdLessThan(Integer min, Integer max); //id>= min AND id<=max List<Knowledge> findByIdBetween(Integer min,Integer max); //id==id Knowledge findByIdIs(Integer id); //id==id Knowledge findByIdEquals(Integer id); //And Or Between(a>=? AND ?<=? ) //GreaterThan(>=) LessThan(<=) //判断空值 IsNull IsNotNull NotNull //模糊查询 Like NotLike //Is Not Equals //OrderBy //In NotIn //TRUE FALSE /* * 时间日期 After Before * findByStartDateAfter * where x.startDate > ?1(After) * */ //StartingWith EndingWith Containing //IgnoreCase //top /* * 注解 * @Query * @Param * */ @Query("from Knowledge where content like %:content%") List<Knowledge> findKnowledgeByContent(@Param("content") String content); @Query(value = "select * from knowledge where content like %:content%",nativeQuery =true) List<Knowledge> findKnowledgeByTitle(@Param("content") String content); @Modifying //修改查询,标记为更新 @Transactional @Query("update Knowledge set content =:content where id =:id") int updateKnowledge(@Param("content") String content,@Param("id") int id); }
-
使用
package com.example.jpademo; import com.example.jpademo.dao.KnowledgeDao; import com.example.jpademo.entity.Knowledge; import org.junit.jupiter.api.Test; 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.jpa.repository.JpaRepository; import javax.annotation.Resource; import java.util.List; import java.util.Optional; @SpringBootTest class JpaDemoApplicationTests { @Resource KnowledgeDao knowledgeDao; @Test void contextLoads() { Knowledge knowledge=new Knowledge(); //根据ID返回单个实体 System.out.println("根据ID返回单个实体-->"+knowledgeDao.findById(97)); //根据ID返回实体是否存在 System.out.println("返回实体是否存在-->"+knowledgeDao.existsById(97)); //返回实体总数 System.out.println("实体总数-->"+knowledgeDao.count()); //分页返回实体 Sort sort = Sort.by(Sort.Order.desc("lastmodified")); System.out.println("第一页数据"); Pageable pageable = PageRequest.of(0, 2,sort); knowledgeDao.findAll(pageable).forEach(System.out::println); //使用方法命名查询 knowledgeDao.findByIdGreaterThanAndIdLessThan(94,100).forEach(System.out::println); knowledgeDao.findByIdBetween(95,97).forEach(System.out::println); //增删改 //修改 //获取实体 knowledge=knowledgeDao.findById(97).get(); knowledge.setTitle("SQL不太难"); knowledge.setId(null); //根据id判断添加或修改 Knowledge save = knowledgeDao.save(knowledge); System.out.println(save); //删除 knowledgeDao.delete(knowledge); knowledgeDao.findKnowledgeByContent("Java").forEach(System.out::println); knowledgeDao.findKnowledgeByTitle("Java").forEach(System.out::println); System.out.println(knowledgeDao.updateKnowledge("第二次更新的测试内容", 97)); } }