Django ORM到Spring Hibernate的映射

对于在spring / hibernate中包含User实体的userRepository,最接近的命令(如果有命令)是什么?

  1. 通过PK / ID获取对象: User.objects.get(id=2)

  2. 通过字段获取对象: User.objects.get(name="david", age=20)

  3. 按字段获取对象: User.objects.filter(name="david")

  4. 按字段删除对象: User.objects.filter(name="david").delete)

  5. 通过字段更新对象: User.objects.filter(name="david").update(name="dave")

我将如何在Java / Spring中从UserRepository中执行上述操作:

public interface UserRepository extends JpaRepository<User, Integer> {
}


千巷猫影
浏览 105回答 1
1回答

猛跑小猪

UserRepository像这样更新您的内容:public interface UserRepository extends JpaRepository<User, Integer> {&nbsp; &nbsp; User findOneByNameAndAge(String name, int age); // Answer point 2&nbsp; &nbsp; List<User> findByName(String name); // Answer point 3&nbsp; &nbsp; @Modifying&nbsp; &nbsp; @Query("delete from User u where u.name = ?1")&nbsp; &nbsp; int deleteByName(String name); // Answer point 4&nbsp; &nbsp; @Modifying&nbsp; &nbsp; @Query("update User u set u.name = ?1 where u.name = ?2")&nbsp; &nbsp; int updateByName(String newName, String oldName); // Answer point 5}请注意,对于您的问题的第1点,JpaRepository已经为您提供了此方法:userRepository.findOne(2);使用方法如下:// Provide necessary annotations..public class UserRepositoryIntTest {&nbsp; &nbsp; @Autowired UserRepository userRepository;&nbsp; &nbsp; @Test&nbsp; &nbsp; public void testThemAll() {&nbsp; &nbsp; &nbsp; &nbsp; this.userRepository.findOne(2); // 1&nbsp; &nbsp; &nbsp; &nbsp; this.userRepository.findOneByNameAndAge("david", 20); // 2&nbsp; &nbsp; &nbsp; &nbsp; this.userRepository.findByName("david"); // 3&nbsp; &nbsp; &nbsp; &nbsp; this.userRepository.deleteByName("david"); // 4&nbsp; &nbsp; &nbsp; &nbsp; this.userRepository.updateByName("dave", "david"); // 5&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java