Skip to content

Instantly share code, notes, and snippets.

@diyfr
Last active November 20, 2017 13:15
Show Gist options
  • Save diyfr/aac46e38dadc2779aacec40e2ad67120 to your computer and use it in GitHub Desktop.
Save diyfr/aac46e38dadc2779aacec40e2ad67120 to your computer and use it in GitHub Desktop.
Use javax.persistence.Column in SQL2o project

add dependency in pom.xml

        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>persistence-api</artifactId>
            <version>1.0.2</version>
        </dependency>

Use @Column annotation in your object

import javax.persitence.Column;

public MyObject{

  @Column(name "tech_id")
  long techId;
}

In your query add setColumnMappings

result = con.createQuery("SELECT * FROM myobject WHERE tech_id=:id")
  .addParameter("id", issue.getTechId())
  .setColumnMappings(ColumnMapping.getMapping(MyObject.class))
  .executeAndFetchFirst(MyObject.class);
package fr.diyfr.sql2o.helper;
import javax.persistence.Column;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class ColumnMapping {
public static Map<String, String> getMapping(Class<?> entity) {
Map<String, String> result = null;
if (entity != null) {
result = new HashMap<String, String>(entity.getDeclaredFields().length);
for (Field field : entity.getDeclaredFields()) {
String name = null;
Annotation[] annotations = field.getAnnotations();
for (Annotation a : annotations) {
if (a.annotationType() == Column.class) {
name = ((Column) a).name();
break;
}
}
if (name == null || name.isEmpty()) {
// Update with your database server.
name = field.getName().toLowerCase();
}
result.put(name, field.getName());
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment