Skip to content

Instantly share code, notes, and snippets.

@dungdm93
Created August 31, 2015 08:15
Show Gist options
  • Save dungdm93/9f3a8b29ec8fd48b3d6f to your computer and use it in GitHub Desktop.
Save dungdm93/9f3a8b29ec8fd48b3d6f to your computer and use it in GitHub Desktop.
[Java][JPA] xml vs. annotation models mapping
package com.gem.demo.database.model;
public class Company {
public int id;
public String name;
public String address;
...
@Override
public String toString() {
return String.format("Company #%d: %s (at %s)", id, name, address);
}
}
package com.gem.demo.database.model;
import javax.persistence.*;
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int id;
public String firstName;
public String lastName;
public double salary;
...
@Override
public String toString() {
return String.format("Employee #%d : %s %s (%f)", id, firstName, lastName, salary);
}
}
<?xml version="1.0" encoding="UTF-8"?>
<entity-mappings
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/persistence/orm"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence/orm orm_2_0.xsd"
version="2.0">
<description>The minimal mappings for a persistent entity in XML.</description>
<package>com.gem.demo.database.model</package>
<entity name="Company" class="com.gem.demo.database.model.Company" access="FIELD">
<table name="COMPANY"/>
<attributes>
<id name="id">
<generated-value strategy="IDENTITY"/>
</id>
<basic name="name">
<column name="COMPANY_NAME" length="100"/>
</basic>
<basic name="address">
</basic>
</attributes>
</entity>
</entity-mappings>
<?xml version="1.0" encoding="UTF-8"?>
<persistence
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/persistence"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_2_0.xsd"
version="2.0">
<persistence-unit name="acme" transaction-type="RESOURCE_LOCAL">
<description>Persistence Unit</description>
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.gem.demo.database.model.Employee</class>
<!-- If mappig file is "orm.xml", no need to inject it into "persistence.xml" -->
<mapping-file>META-INF/models-mapping.xml</mapping-file>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/sample-jpa"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="qwerty"/>
<!-- EclipseLink Configuration -->
<property name="eclipselink.ddl-generation" value="create-tables"/>
<property name="eclipselink.logging.level.sql" value="FINE"/>
</properties>
</persistence-unit>
</persistence>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment