zoukankan      html  css  js  c++  java
  • Spring Data JPA @Column 注解无效 打出的语句有下划线



    最近再写一个Restful API的小例子,遇到这样一个问题,在Spring Boot 下使用CrudRepository,总是提示如下错误:

    Caused by: java.sql.SQLSyntaxErrorException: Unknown column 'userprofil0_.real_name' in 'field list'
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:536)
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:513)
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:115)
        at com.mysql.cj.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:1983)
        at com.mysql.cj.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1826)
        at com.mysql.cj.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1923)
        at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:70)
        ... 76 more
    

    而我的Bean这样写的:

    @Entity
    @Table(name = "eb_user_profile")
    public class UserProfile {    
        @Id    
        @GeneratedValue(strategy = GenerationType.IDENTITY)    
        @Column(name = "UserID")    
        private Long UserID;    
        @Column(name = "UserName")    
        private String UserName;    
        @Column(name = "RealName")   
        private String RealName;    
    
        public UserProfile() {    }    
    
        public UserProfile(String userName, String realName) {        
            UserName = userName;        
            RealName = realName;    
        }
    
        getter... 
        setter...
    }
    

    于是spring.jpa.show-sql = true 打印SQL如下

    Hibernate: select userprofil0_.userid as userid1_0_0_, userprofil0_.real_name as real_nam2_0_0_, userprofil0_.user_name as user_nam3_0_0_ from eb_user_profile userprofil0_ where userprofil0_.userid=?
    

    啊咧咧,注解明明写好了,为何映射的SQL还是带下划线的?

    最后发动老夫的望气之术,终于在茫茫网海中找到这样一段文字:

    addUnderscores 用于处理 当表名和列名在Java的种规则符合 UserNameTable(表)和 userNameColumn(列),就会被解析为user_name_table 和 user_name_column ,具体return的处理的是propertyToColumnName。 but呢,如果一旦配置了这个规则,(spring +jpa配置如下:
    spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy)
    就会忽略了注释中的@Column中的name,其实这个name地方就是为了映射数据库字段,结果配置了这个就不care了。
    http://blog.csdn.net/dracotianlong/article/details/27834143

    因为配置了org.hibernate.cfg.ImprovedNamingStrategy 策略,因此当列名符合驼峰命名法时,注解就无效了。

    解决方案:
    1. @Column中的值变为小写。
    2. 继承ImprovedNamingStrategy 自定义策略。

    作者:naiive
    链接:https://www.jianshu.com/p/ba87a9ee6001
    來源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 相关阅读:
    C# 5注释
    C# 4关键字
    C# 3练习题
    python之子类调用父类的同名属性和方法
    python之继承
    python之对象删除和输出
    python之r,w,a
    python之类中的方法和属性
    python之面向对象
    python之os对文件的操作
  • 原文地址:https://www.cnblogs.com/suizhikuo/p/8446467.html
Copyright © 2011-2022 走看看