2

As I am trying to map Entity to tables using JPA (Hibernate implementation) I found something confusing

when i use annotation on getter, things are OK

@Column(name = "main_battery_voltage", precision = 2)
public float getMainBatteryVoltage() {
    return mainBatteryVoltage;
}

but When I try the same thing on field, field name is used and attribute

@Column(name = "main_battery_voltage", precision = 2)
private float mainBatteryVoltage;

System ignores name attribute, runs with column name mainBatteryVoltage in DB and consequently failed task.

I am using MySQL and this is the persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
    <persistence-unit name="SolarPersistenceUnit">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>com.cs.solar.db.entity.User</class>
        <class>com.cs.solar.db.entity.Lamp</class>
        <class>com.cs.solar.db.entity.Project</class>
        <properties>
            <property name="hibernate.dialect"     value="org.hibernate.dialect.MySQL5Dialect"/>
            <!--<property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>-->
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/SOLAR"/>
            <property name="hibernate.connection.username" value="root" />
            <property name="hibernate.connection.password" value="admin" />
            <property name="hibernate.connection.autocommit" value="false"/>
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.max_fetch_depth" value="3"/>
        </properties>
    </persistence-unit>
     <persistence-unit name="TestSolar" />
</persistence>

Although it works now, I am curious what cause this problem, thank

Korben
  • 734
  • 1
  • 7
  • 26
  • Which Hibernate version are you using? – rbento Oct 15 '12 at 02:30
  • I am using Hibernate 4.0 – Korben Oct 15 '12 at 02:43
  • Remove the name attribute, namings should take its defaults, it is camelCase to camel_case underscored. Also, make sure, the field access type is set. And try doing this not with a float, but with a string for example. – d1e Oct 15 '12 at 07:14

1 Answers1

0

You can find a short explanation here:
Hibernate Annotation Placement Question

The point is:
"the access type used by Hibernate will be field or property. The EJB3 spec requires that you declare annotations on the element type that will be accessed, i.e. the getter method if you use property access, the field if you use field access. Mixing EJB3 annotations in both fields and methods should be avoided. Hibernate will guess the access type..."

Community
  • 1
  • 1
Gergely Bacso
  • 14,243
  • 2
  • 44
  • 64