持久化 XML 文件在使用 Spring Boot 中的等效 Java 配置:

huangapple 未分类评论42阅读模式
英文:

persistence xml file equivalent java configuration with spring boot

问题

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
             xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
             http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="dtmowliance">

        <class>com.lma.flad.ClassB</class>
        <class>com.lma.flad.ClassC</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <shared-cache-mode>ENABLE_SELECTIVE</shared-cache-mode>
        <properties>
            <property name="hibernate.cache.region.factory_class"
                      value="org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
        </properties>
    </persistence-unit>
</persistence>

在这种情况下,Hibernate 仅会分析持久化 XML 文件中列出的类(ClassA 和 ClassB)。

如何在 Spring Boot 中使用 Java 配置创建等效的 persistence.xml 呢?

英文:

I am working on a spring boot project in which I have entities with @Entity Decorator which do not have @Id decorator because they are views and not tables. this is why I have a persistence.xml file which says that the classes processed hibernate here

#Classe A

package com.lma.flad;
    @Entity
      class ClassA{
          private String name;
          private String surName
       }

#classe B

package com.lma.flad;
    @Entity
      class ClassB{
          @Id
          private Long id
          private String name;
          private String surName
       }

#classe C

package com.lma.flad;
    @Entity
      class ClassC{
          @ID
          private Long id
          private String name;
          private String surName
       }

persistance.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;persistence version=&quot;2.0&quot;
             xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema- 
             instance&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/persistence 
             http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    &lt;persistence-unit name=&quot;dtmowliance&quot;&gt;

        &lt;class&gt;com.lma.flad.ClassB&lt;/class&gt;
        &lt;class&gt;com.lma.flad.ClassC&lt;/class&gt;
        &lt;exclude-unlisted-classes&gt;true&lt;/exclude-unlisted-classes&gt;
        &lt;shared-cache-mode&gt;ENABLE_SELECTIVE&lt;/shared-cache-mode&gt;
        &lt;properties&gt;
            &lt;property name=&quot;hibernate.cache.region.factory_class&quot;
                      value=&quot;org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory&quot;/&gt;
            &lt;property name=&quot;hibernate.dialect&quot; value=&quot;org.hibernate.dialect.Oracle10gDialect&quot;/&gt;
        &lt;/properties&gt;
    &lt;/persistence-unit&gt;
&lt;/persistence&gt;

<br>
in this case, hibernate will only analyze the classes found in the persistence xml file (classA and Class B)
<br>
How i can do the persistence.xml with java config in spring boot

答案1

得分: 0

自从您创建了实体类(JPA),您需要按照以下步骤进行操作:

  1. 创建 JPA 仓库

导入:适用于三个实体

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

为每个实体创建仓库

@Repository
public interface ClassARepository extends JpaRepository<ClassA, Long> {
 
}
@Repository
public interface ClassBRepository extends JpaRepository<ClassB, Long> {
 
}
@Repository
public interface ClassCRepository extends JpaRepository<ClassC, Long> {
 
}
  1. 属性配置:

配置 application.properties 文件以将数据库连接到 JPA 代码。

spring.datasource.url=jdbc:h2:file:~/test
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
 
# 启用 H2 控制台
spring.h2.console.enabled=true
 
# 自定义 H2 控制台 URL
spring.h2.console.path=/h2-console

# 打开统计信息并记录 SQL 语句
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.hibernate.ddl-auto=create-drop
 
# 如果希望查看非常详细的日志
spring.jpa.properties.hibernate.generate_statistics=true
logging.level.org.hibernate.type=trace
logging.level.org.hibernate.stat=debug
  1. 使用 Spring Boot 测试与数据库和 JPA 的连接
import java.util.Optional;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
import <your-path>.entity.ClassA;// 根据需要更改
import <your-path>.entity.ClassB;// 根据需要更改
import <your-path>.entity.ClassA;// 根据需要更改
import <your-path>.repository.ClassARepository;// 根据需要更改
import <your-path>.repository.ClassBRepository;// 根据需要更改
import <your-path>.repository.ClassCRepository;// 根据需要更改
 
@SpringBootApplication
public class DB2JPAApplication implements CommandLineRunner {
 
    private Logger logger = LoggerFactory.getLogger(this.getClass());
     
    @Autowired
    ClassARepository classArepository;

    @Autowired
    ClassBRepository classBrepository;

    @Autowired
    ClassCRepository classCrepository;
     
    public static void main(String[] args) {
        SpringApplication.run(DB2JPAApplication.class, args);
    }
 
    @Override
    public void run(String... args) throws Exception 
    {       
        Optional<ClassAEntity> classC = repository.findById(2L);
 
        logger.info("ClassC id 2 -> {}", classC.get());

        Optional<ClassAEntity> classB = repository.findById(2L);
 
        logger.info("ClassB id 2 -> {}", classB.get());
    }

注意:

  • 您的 ClassA 没有 @Id。JPA 要求必须有一个 ID 列。

  • DB2JPAApplication 类中更改实体和仓库的导入。

英文:

Since you have created the Entity classes (JPA), you have to follow the subsequent steps:

  1. Create JPA Repository

Imports: Common for 3 entities

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

Repository for each entity

@Repository
public interface ClassARepository extends JpaRepository&lt;ClassA, Long&gt; {
 
}
@Repository
public interface ClassBRepository extends JpaRepository&lt;ClassB, Long&gt; {
 
}
@Repository
public interface ClassCRepository extends JpaRepository&lt;ClassC, Long&gt; {
 
}
  1. Properties Configuration:

Configuring application.properties file to connect database to JPA code.

    spring.datasource.url=jdbc:h2:file:~/test
    spring.datasource.driverClassName=org.h2.Driver
    spring.datasource.username=sa
    spring.datasource.password=
    spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
     
    # Enabling H2 Console
    spring.h2.console.enabled=true
     
    # Custom H2 Console URL
    spring.h2.console.path=/h2-console
    
    #Turn Statistics on and log SQL stmts
     
    spring.jpa.show-sql=true
    spring.jpa.properties.hibernate.format_sql=true
    spring.jpa.hibernate.ddl-auto=create-drop
     
    #If want to see very extensive logging
    spring.jpa.properties.hibernate.generate_statistics=true
    logging.level.org.hibernate.type=trace
    logging.level.org.hibernate.stat=debug
  1. Spring Boot to test your connectivity with database and JPA

    import java.util.Optional;

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;

    import <your-path>.entity.ClassA;//change accordingly
    import <your-path>.entity.ClassB;//change accordingly
    import <your-path>.entity.ClassA;//change accordingly
    import <your-path>.repository.ClassARepository;// change accordingly
    import <your-path>.repository.ClassBRepository;// change accordingly
    import <your-path>.repository.ClassCRepository;// change accordingly

    @SpringBootApplication
    public class DB2JPAApplication implements CommandLineRunner {

     private Logger logger = LoggerFactory.getLogger(this.getClass());
    
     @Autowired
     ClassARepository classArepository;
    
     @Autowired
     ClassBRepository classBrepository;
    
     @Autowired
     ClassCRepository classCrepository;
    
     public static void main(String[] args) {
         SpringApplication.run(DB2JPAApplication.class, args);
     }
    
     @Override
     public void run(String... args) throws Exception 
     {       
         Optional&lt;ClassAEntity&gt; classC = repository.findById(2L);
    
         logger.info(&quot;ClassC id 2 -&gt; {}&quot;, classC.get());
    
         Optional&lt;ClassAEntity&gt; classB = repository.findById(2L);
    
         logger.info(&quot;ClassB id 2 -&gt; {}&quot;, classB.get());
     }
    

NOTE:

  • Your classA has no @Id. JPA makes it mandatory to have an ID column.

  • Change Entity and repository imports in DB2JPAApplication class

huangapple
  • 本文由 发表于 2020年4月4日 18:08:35
  • 转载请务必保留本文链接:https://java.coder-hub.com/61026536.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定