【问题标题】:Spring Boot + JPA + Hibernate : Insert and fetch list of entities at onceSpring Boot + JPA + Hibernate:一次插入和获取实体列表
【发布时间】:2017-05-08 09:06:43
【问题描述】:

我正在使用Spring Boot + JPA + Hibernate。我有实体/表用户。如何创建CrudRepositoty 一次插入用户列表?另外如何将结果作为某些查询的列表获取?

【问题讨论】:

    标签: database hibernate spring-boot spring-data-jpa


    【解决方案1】:

    制作一个实现 crudRepository 的接口

    import java.util.List;
    
    import org.springframework.data.repository.CrudRepository;
    import org.springframework.stereotype.Repository;
    
    
    @Repository
    public interface UserRepo extends CrudRepository<User, Long>  {
    
    
    
         List<User> findAll();
    
    }
    

    这里 CrudRepository 为您的自定义函数隐式创建查询,例如上面代码中的 findAll()

    服务类

    @Service("userservice")
    public class UserService {
    
        @Autowired
        UserRepo rep;
    
        @Transactional
        public ArrayList<User> findAll()
        {
    
            return (ArrayList<User>) rep.findAll();
    
        }
    }
    

    以同样的方式你可以将你的对象保存为 rep.save(User object)

    【讨论】:

    • 谢谢维克拉姆。一个澄清,要获得具有相同名称的用户列表方法将是 List findByName(String name) 。我说的对吗?
    • 谢谢大家。如何获取同名用户的数量?
    • 做一些研究你会在互联网上得到它:)
    猜你喜欢
    • 2021-02-09
    • 2017-11-20
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    • 2020-12-17
    相关资源
    最近更新 更多