框架:spring boot
工具: Spring Tool Sites
1、新建spring boot项目
右键-->New --> Spring Starter Project,数据库选择jpa即可,或者自己导入JPA maven仓库也行
2、修改配置文件application.properties,配置数据库信息
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/wshop?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false
3、查询方法定义规则
例:
import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.Repository; import org.springframework.data.repository.query.Param; import com.sun.dao.SysUser; public interface SysUserRepository extends Repository<SysUser,Integer> { List<SysUser> findById(Integer id); List<SysUser> findByUsernameLike(String name); }
3、Query自定义查询
import java.util.List; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.Repository; import org.springframework.data.repository.query.Param; import com.sun.dao.SysUser; public interface SysUserRepository extends Repository<SysUser,Integer> { //自定义(随便写) @Query(value="select * from s_user",nativeQuery=true) List<SysUser> findAll(); //占位符形式 @Query("select o from SysUser o where username=?1 and state =?2") List<SysUser> findUserByNameAndState(String name,String state); //变量形式 @Query("select o from SysUser o where username=:name and state =:state") List<SysUser> findUserByNameAndState1(@Param("name")String name,@Param("state")String state); }
4、事务操作
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import cn.sun.domain.Sys_news; public interface NewsRepository extends JpaRepository<Sys_news, String> { @Modifying @Query("update sys_news set view_count=view_count+1 where news_id=?1") void viewAddOne(String news_id); }
注意:注解@Modifying是必须要写的,然后需要在service方法上加@Transactional
@Transactional public void deleteAutoMarketById(String id) { autoMarketRepository.deleteAutoMarketById(id); }
5、JpaSpecificationExecutor接口(比较常用,带分页、排序、查询条件)