目前项目用到springboot + jpa进行持久层处理,就写了几个增删改查的小demo
直接上代码
新增:
//1、新增
Dog dog = new Dog();
dog.setName("李哥");
dog.setCode(123L);
dog.setAge(66);
//dog.setId(16L);
Dog dog1 = dogDao.save(dog);
System.out.println(dog1.toString());
修改:
//2、注解方式修改
Integer dog1 = dogDao.updateDog(77L, "李哥", 16L);
System.out.println(dog1.toString());
//3、编程方式修改(注意:此种方式必须在调用update的方法上加@Transactional,不加会报错)
Long age = 88L;
String name = "周姐";//你懂的
Long id = 16L;
String sql = "update dog set age = '" + age + "' ,name = '" + name +"' where id = '" + id + "'";
//获取session
SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
//获取connection
Connection connection = session.connection();
int i = 0;
try {
connection.setAutoCommit(false);
i = entityManager.createNativeQuery(sql).executeUpdate();
connection.commit();
connection.setAutoCommit(true);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
System.out.println(i);
//dao层代码如下
public interface DogDao extends JpaRepository<Dog, Long> {
@Query(nativeQuery = true,value = "update dog set age = ?1 ,name = ?2 where id = ?3")
@Modifying
@Transactional
Integer updateDog(Long age,String name,Long id);
}
删除:
//批量删除,1、调用deleteInBatch方法批量删除
List<Long> longList = new ArrayList<>();
longList.add(1L);
longList.add(2L);
longList.add(3L);
try {
//获取session
SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
//获取connection
Connection connection = session.connection();
connection.setAutoCommit(false);
List<Dog> byId = dogDao.findAllById(longList);
dogDao.deleteInBatch(byId);
connection.commit();
connection.setAutoCommit(true);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
//
// //2、通过原生sql批量删除
int i = entityManager.createNativeQuery("delete from dog where id in (" + 10L + "," + 11L + ")").executeUpdate();
System.out.println(i);
查询:
//通过hql查询
List<Dog> dogs = entityManager.createQuery("from Dog d", Dog.class).getResultList();
dogs.stream().forEach(System.out::println);
希望可以帮助到你,谢谢!