programing

스프링 부트에서의 휴지 상태 필드 이름 지정 문제(이름 지정 전략)

mailnote 2023. 3. 12. 11:01
반응형

스프링 부트에서의 휴지 상태 필드 이름 지정 문제(이름 지정 전략)

이 코드는 플레인 스프링에서는 동작하지만 스프링 부트(v1.3.3)에서는 동작하지 않는 것에 주의해 주세요.이것은 동작하는 스프링 앱에서 Import한 것이기 때문에, 부족한 점이 있는 것입니까.다음 코드는 스프링 부트 앱에서 가져온 것입니다.

@Entity
@Table(name="project")
public class Project implements Serializable{

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id")
    private int id;

    @Column(name="teamId")
    private int teamId;

    //private String Rentabiliteit;

    @Column
    //@Index(name="IProject_status",columnNames="Status")
    private String status;

    @Column
    //@Index(name="IProject_naam",columnNames="Naam")
    private String naam;
    //public Prototype m_Prototype;
    //public Team m_Team;

}

SQL

CREATE TABLE IF NOT EXISTS `project` (
`id` int(11) NOT NULL,
`teamId` int(11) DEFAULT NULL,
`status` varchar(255) DEFAULT NULL,
`naam` varchar(255) DEFAULT NULL
 ) ENGINE=InnoDB AUTO_INCREMENT=43 DEFAULT CHARSET=latin1;

에러

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:           
 Unknown column 'project0_.team_id' in 'field list'

편집: Application.yml

spring:

mvc:
  view:
    prefix: /WEB-INF/jsp/
    suffix: .jsp

datasource:
    url: jdbc:mysql://localhost:3306/oxyplast
    username: oxyplastuser
    password: oxyplastuserpw

jpa:
  properties:
    hibernate:
      current_session_context_class: org.springframework.orm.hibernate4.SpringSessionContext 
      namingStrategy: org.hibernate.cfg.DefaultNamingStrategy

스프링 부트 1.4 이후

1.4부터는 휴지 상태5로의 전환에 의해 명명 전략이 갱신되었습니다.SpringPhysicalNamingStrategy디폴트값 1.3에 매우 가깝습니다.

다음 항목도 참조하십시오.


이전 버전

Spring Boot에서는 디폴트 명명 전략으로서를 제공하고 있습니다.이를 통해 하이버네이트 검색은team_idcolumn (에서 선택)int teamId필드)를 참조해 주세요.이 열은 테이블에 존재하지 않기 때문에 에러의 원인이 됩니다.휴지 상태 문서:

대소문자를 혼합한 이름보다 밑줄 삽입을 선호하는 향상된 이름 지정 전략

두 가지 옵션이 있습니다.

  1. 이름을 명시적으로 지정합니다.@Column(name="teamId")이전 Boot 버전에서는 이 버그가 있었습니다.이제 없습니다.

  2. Spring Boot 속성에서 이름 지정 전략을 변경하고 camelCase를 snake_case로 변환하지 않고 그대로 유지하도록 지시합니다.

Spring Boot 2.0.2 및 휴지 상태 5.3.4 를 사용하고 있는 경우는, 다음의 속성을 설정하면 문제가 해결됩니다.

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

아래 전략이 나에게 효과가 있었다

spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.DefaultComponentSafeNamingStrategy

최신 버전:

    spring-boot-starter-data-jpa: ➡ 1.5.2.RELEASE
    hibernate-core:5.0.12.Final

이 반

PhysicalNamingStrategyStandardImpl

휴지 상태 속성을 사용하려면 를 확장 및 추가해야 합니다.

여기 완전한 작동 버전이 있습니다.

    public class PhysicalNamingStrategyImpl extends PhysicalNamingStrategyStandardImpl implements Serializable {

    public static final PhysicalNamingStrategyImpl INSTANCE = new PhysicalNamingStrategyImpl();

    @Override
    public Identifier toPhysicalTableName(Identifier name, JdbcEnvironment context) {
        String nameModified;
        // Do whatever you want with the name modification
        return new Identifier(nameModified, name.isQuoted());
    }

}

    @Override
    public Identifier toPhysicalColumnName(Identifier name, JdbcEnvironment context) {
         String nameModified;
        // Do whatever you want with the name modification
        return new Identifier(nameModified, name.isQuoted());
    }

데이터 소스를 설정할 때는, 이것을 휴지 상태에 링크 해 주세요.

properties.put("hibernate.physical_naming_strategy", "my.Package.PhysicalNamingStrategyImpl");

여기에서는 데이터 소스 설정의 풀 동작 버전을 보여 줍니다.

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;


@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactory",
        basePackages = { "com.xxxxxx.repository" }
)
public class SharedDataSourceConfig {

    @Value("${startup.ddl-auto}")
    String hbm2ddl;

    @Primary
    @Bean(name = "dataSource")
    @ConfigurationProperties("spring.datasource.shared")
    public DataSource customerDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Primary
    @Bean(name = "entityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(
            EntityManagerFactoryBuilder builder,
            @Qualifier("dataSource") DataSource dataSource) {
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put("hibernate.hbm2ddl.auto", hbm2ddl);
        properties.put("hibernate.physical_naming_strategy", "my.package.PhysicalNamingStrategyImpl");
        return builder
                .dataSource(dataSource)
                .packages(PackageScannerHelper.getPackagesToScan())
                .persistenceUnit("shared")
                .properties(properties)
                .build();
    }

    @Primary
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(
            @Qualifier("entityManagerFactory") EntityManagerFactory
                    entityManagerFactory
    ) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

이것은 스프링 부트 1.4.0과 하이버네이션 entitymanager 4.3.8에서 동작했습니다.최종

application.properties

spring.jpa.context.naming.context-context=spring.context.boot.model.naming.naming을 지정합니다Implicit Naming StrategyLegacyJpaImpl spring.jpa.hibernate.naming.physical-displaces=displacate.boot.model.naming.Physical Naming Strategy Standard Impl

application.properties

spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.DefaultComponentSafeNamingStrategy

위의 속성으로 충분합니다.하이버네이션 4.3.11최종 스프링 부트 1.4.2풀어주다

언급URL : https://stackoverflow.com/questions/36451620/hibernate-field-naming-issue-with-spring-boot-naming-strategy

반응형