【问题标题】:Connecting Java Webapplication to MySQL with JPA and/or Hibernate?使用 JPA 和/或 Hibernate 将 Java Web 应用程序连接到 MySQL?
【发布时间】:2015-04-22 10:25:54
【问题描述】:

几天前我听说了 spring-boot。 所以我开始从零开始设置我的项目,包括 jpa 并且不使用现有项目中的旧设置。但是现在在我所学到的和我所读到的关于 spring boot 和 jpa 的“简单设置”之间存在一个理解问题。

通常我的项目有这种结构。

  1. 型号(以汽车为例)
  2. ModelDao(带有以下代码示例的 CarDao)

    @Component
    public class CarDao {
        /** The Hibernate session factory. */
        @Autowired
        private SessionFactory sessionFactory;
        @Transactional
        public void save(Car car) {
            sessionFactory.getCurrentSession().saveOrUpdate(car);
        }
    
  3. 适用于 DAO 的 CarServiceImpl(包括 findAll()getCarById()saveCar(Car car) 等方法)

但现在我只阅读了有关 @Entity 和 JPA 存储库的信息。 因为我有@Entity-Annotation,所以说我不需要模型和 dao 是否正确?我的 ServiceImples 和 JPA 存储库具有相同的功能吗? SessionFactory 发生了什么?都是自动管理的吗?

【问题讨论】:

    标签: java hibernate jpa


    【解决方案1】:

    如果要使用 JPA-Repositories,则不需要 DAO。
    也不需要 Session-Factory。
    只需要一个类作为模型,一个接口作为存储库,就完成了。

    示例:

    @Entity
    @Table(name="COUNTRY")
    public class Country {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name="COUNTRY_ID", nullable = false)
        private Integer country_id;
    
        @Column(name="COUNTRY_CODE")
        private String country_code;
        //Add getter and setter
    }
    

    界面

    public interface CountryRepository  extends PagingAndSortingRepository<Country, Integer> {
    
    }
    

    是的,您需要在 spring.xml 中配置上述存储库的位置

     <jpa:repositories base-package="com.repository" />
    

    在spring.xml中创建事务管理器

    并使用以下代码访问它

    ApplicationContext ctx = new ClassPathXmlApplicationContext(
                    "spring.xml");
            countryRepository = (CountryRepository) ctx.getBean("countryRepository");
            Country country = countryRepository.findOne(1);
    

    【讨论】:

      【解决方案2】:
      Is it right to say that I dont need models and dao's because I have the @Entity-Annotation?
      

      @Entity 注解用于 POJO 模型。 @Entity 将 POJO 即类属性映射到 db 表。如果摆脱模型,您将如何编写业务逻辑。

      服务层、DAO层都是应用程序设计的组成部分。他们有其特定的作用。众所周知,ServiceImpl 管理事务,而 DAO/Repository 层管理与 db 的通信。

      这里你的CarDao 类应该用@Repository 注释进行注释。它是一个 DAOImpl 类。

      你所有的事务方法都应该移到服务层。

      And my ServiceImples and JPA-repositorys have the same functionality? 
      

      不,正如我已经说过的那样,它们具有特定的各自功能。它们不一样。

      What happend with the SessionFactory? Is all managed automatically?
      

      SessionFactory 总是被注入到 DAO 层中。您可以自己管理会话,也可以让 hibernate 管理会话。

      【讨论】:

        猜你喜欢
        • 2014-09-30
        • 2015-12-14
        • 2010-09-07
        • 2014-05-24
        • 1970-01-01
        • 1970-01-01
        • 2014-11-26
        • 1970-01-01
        • 2023-03-27
        相关资源
        最近更新 更多