package com.nulichengong.chapter13.controller;
import com.nulichengong.chapter13.entity.UserEntity;
import com.nulichengong.chapter13.jpa.UserJPA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserJPA userJPA;
//jpa查询
@RequestMapping(value = "/list")
public List<UserEntity>list(){
return userJPA.findAll();
}
//jpa增加
@RequestMapping(value = "/add")
public List add(){
UserEntity userEntity=new UserEntity();
userEntity.setName("测试");
userEntity.setAddress("测试地址");
userEntity.setAge(21);
userEntity.setPwd("123");
userJPA.save(userEntity);
return userJPA.findAll();
// return "添加成功";
}
//jpa删除
@RequestMapping(value = "/delete")
public String delete(Long id){
userJPA.deleteById(id);
return "用户信息删除成功";
}
//自定义删除 query
@RequestMapping(value = "/delet")
public String delet(Long id){
userJPA.delete(id);
return "用户信息删除成功";
}
@RequestMapping(value="/deleteWhere")
public String deleteWhere(){
userJPA.deleteQuery("5","5");
return "自定义SQl删除数据成功";
}
}
package com.nulichengong.chapter13.jpa;
import com.nulichengong.chapter13.entity.UserEntity;
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 javax.transaction.Transactional
public interface UserJPA extends JpaRepository<UserEntity,Long> {
@Transactional //必须添加这2个注解
@Modifying //必须添加这2个注解
@Query(value="delete from t_user where t_id=?1",nativeQuery = true)
public void delete( @Param(value = "id") Long id);
@Transactional
@Modifying
@Query(value="delete from t_user where t_name=?1 and t_pwd=?2",nativeQuery = true)
public void deleteQuery(String name,String pwd);