Can you please help me to map this class using Hibernate?
public class MyClass{
private Long id;
private String name;
private int[] values;
...
}
I'm using PostgreSQL and the column type in the table is integer[]
How my array should be mapped?
Hibernate (and JPA) can't directly map the PostgreSQL array type. See this question for how to proceed if you really need to retain your database structure as it is. This thread has an example of the required custom type.
If you can change your schema, you can let hibernate create an additional table to handle the collection - List<Integer>. Then, depending on the version of hibernate you are using:
JPA 2.0 compliant - use #ElementCollection
JPA 1.0 compliant - use #CollectionOfElements
Hibernate can map only the primitive types. Check under the org.hibernate.type folder of hibernate jar package. int array is not one of them. So you would have to write a custom type that can implement the UserType interface.
public class MyClass{
private Long id;
private String name;
private Integer[] values;
#Type(type = "com.usertype.IntArrayUserType")
public Integer[] getValues(){
return values;
}
public void setValues(Integer[] values){
this.values = values;
}
}
IntArrayUserType.class
package com.usertype.IntArrayUserType;
public class IntArrayUserType implements UserType {
protected static final int[] SQL_TYPES = { Types.ARRAY };
#Override
public Object assemble(Serializable cached, Object owner) throws HibernateException {
return this.deepCopy(cached);
}
#Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
#Override
public Serializable disassemble(Object value) throws HibernateException {
return (Integer[]) this.deepCopy(value);
}
#Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == null) {
return y == null;
}
return x.equals(y);
}
#Override
public int hashCode(Object x) throws HibernateException {
return x.hashCode();
}
#Override
public boolean isMutable() {
return true;
}
#Override
public Object nullSafeGet(ResultSet resultSet, String[] names, SessionImplementor session, Object owner)
throws HibernateException, SQLException {
if (resultSet.wasNull()) {
return null;
}
if(resultSet.getArray(names[0]) == null){
return new Integer[0];
}
Array array = resultSet.getArray(names[0]);
Integer[] javaArray = (Integer[]) array.getArray();
return javaArray;
}
#Override
public void nullSafeSet(PreparedStatement statement, Object value, int index, SessionImplementor session)
throws HibernateException, SQLException {
Connection connection = statement.getConnection();
if (value == null) {
statement.setNull(index, SQL_TYPES[0]);
} else {
Integer[] castObject = (Integer[]) value;
Array array = connection.createArrayOf("integer", castObject);
statement.setArray(index, array);
}
}
#Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
#Override
public Class<Integer[]> returnedClass() {
return Integer[].class;
}
#Override
public int[] sqlTypes() {
return new int[] { Types.ARRAY };
}
When you query for the MyClass entity you can add something like this:
Type intArrayType = new TypeLocatorImpl(new TypeResolver()).custom(IntArrayUserType.class);
Query query = getSession().createSQLQuery("select values from MyClass")
.addScalar("values", intArrayType);
List<Integer[]> results = (List<Integer[]>) query.list();
Maven dependency
The first thing you need to do is to set up the following Hibernate Types Maven dependency in your project pom.xml configuration file:
<dependency>
<groupId>com.vladmihalcea</groupId>
<artifactId>hibernate-types-52</artifactId>
<version>${hibernate-types.version}</version>
</dependency>
Maven ARRAY columns
Assuming you have this table in your database:
create table event (
id int8 not null,
version int4,
sensor_names text[],
sensor_values integer[],
primary key (id)
)
And you want to map it like this:
#Entity(name = "Event")
#Table(name = "event")
#TypeDefs({
#TypeDef(
name = "string-array",
typeClass = StringArrayType.class
),
#TypeDef(
name = "int-array",
typeClass = IntArrayType.class
)
})
public static class Event extends BaseEntity {
#Type( type = "string-array" )
#Column(
name = "sensor_names",
columnDefinition = "text[]"
)
private String[] sensorNames;
#Type( type = "int-array" )
#Column(
name = "sensor_values",
columnDefinition = "integer[]"
)
private int[] sensorValues;
//Getters and setters omitted for brevity
}
The string-array and int-array are custom types which can be defined in the BaseEntity superclass:
#TypeDefs({
#TypeDef(
name = "string-array",
typeClass = StringArrayType.class
),
#TypeDef(
name = "int-array",
typeClass = IntArrayType.class
)
})
#MappedSuperclass
public class BaseEntity {
#Id
private Long id;
#Version
private Integer version;
//Getters and setters omitted for brevity
}
The StringArrayType and IntArrayType are classes offered by the Hibernate Types project.
Testing time
Now, when you insert a couple of entities;
Event nullEvent = new Event();
nullEvent.setId(0L);
entityManager.persist(nullEvent);
Event event = new Event();
event.setId(1L);
event.setSensorNames(
new String[] {
"Temperature",
"Pressure"
}
);
event.setSensorValues(
new int[] {
12,
756
}
);
entityManager.persist(event);
Hibernate is going to generate the following SQL statements:
INSERT INTO event (
version,
sensor_names,
sensor_values,
id
)
VALUES (
0,
NULL(ARRAY),
NULL(ARRAY),
0
)
INSERT INTO event (
version,
sensor_names,
sensor_values,
id
)
VALUES (
0,
{"Temperature","Pressure"},
{"12","756"},
1
)
I have never mapped arrays to hibernate. I always use collections. So, I have slightly changed you class:
public class MyClass{
private Long id;
private String name;
private List<Integer> values;
#Id
// this is only if your id is really auto generated
#GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
return id;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY)
public List<Integer> getValues() {
return values;
}
...
From Hibernate 6.1 Final, basic arrays and collections may now be mapped to database ARRAY types if possible, or alternatively JSON/XML types.
https://in.relation.to/2022/06/14/orm-61-final/
Related
I'm using EclipseLink to run some Native SQL. I need to return the data into a POJO. I followed the instructions at EclipseLink Docs, but I receive the error Missing descriptor for [Class]
The query columns have been named to match the member variables of the POJO. Do I need to do some additional mapping?
POJO:
public class AnnouncementRecipientsFlattenedDTO {
private BigDecimal announcementId;
private String recipientAddress;
private String type;
public AnnouncementRecipientsFlattenedDTO() {
super();
}
public AnnouncementRecipientsFlattenedDTO(BigDecimal announcementId, String recipientAddress, String type) {
super();
this.announcementId = announcementId;
this.recipientAddress = recipientAddress;
this.type = type;
}
... Getters/Setters
Entity Manager call:
public List<AnnouncementRecipientsFlattenedDTO> getNormalizedRecipientsForAnnouncement(int announcementId) {
Query query = em.createNamedQuery(AnnouncementDeliveryLog.FIND_NORMALIZED_RECIPIENTS_FOR_ANNOUNCEMENT, AnnouncementRecipientsFlattenedDTO.class);
query.setParameter(1, announcementId);
return query.getResultList();
}
I found out you can put the results of a Native Query execution into a List of Arrays that hold Objects. Then one can iterate over the list and Array elements and build the desired Entity objects.
List<Object[]> rawResultList;
Query query =
em.createNamedQuery(AnnouncementDeliveryLog.FIND_NORMALIZED_RECIPIENTS_FOR_ANNOUNCEMENT);
rawResultList = query.getResultList();
for (Object[] resultElement : rawResultList) {
AnnouncementDeliveryLog adl = new AnnouncementDeliveryLog(getAnnouncementById(announcementId), (String)resultElement[1], (String)resultElement[2], "TO_SEND");
persistAnnouncementDeliveryLog(adl);
}
You can only use native SQL queries with a class if the class is mapped. You need to define the AnnouncementRecipientsFlattenedDTO class as an #Entity.
Otherwise just create the native query with only the SQL and get an array of the data back and construct your DTO yourself using the data.
Old question but may be following solution will help someone else.
Suppose you want to return a list of columns, data type and data length for a given table in Oracle. I have written below a native sample query for this:
private static final String TABLE_COLUMNS = "select utc.COLUMN_NAME, utc.DATA_TYPE, utc.DATA_LENGTH "
+ "from user_tab_columns utc "
+ "where utc.table_name = ? "
+ "order by utc.column_name asc";
Now the requirement is to construct a list of POJO from the result of above query.
Define TableColumn entity class as below:
#Entity
public class TableColumn implements Serializable {
#Id
#Column(name = "COLUMN_NAME")
private String columnName;
#Column(name = "DATA_TYPE")
private String dataType;
#Column(name = "DATA_LENGTH")
private int dataLength;
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public int getDataLength() {
return dataLength;
}
public void setDataLength(int dataLength) {
this.dataLength = dataLength;
}
public TableColumn(String columnName, String dataType, int dataLength) {
this.columnName = columnName;
this.dataType = dataType;
this.dataLength = dataLength;
}
public TableColumn(String columnName) {
this.columnName = columnName;
}
public TableColumn() {
}
#Override
public int hashCode() {
int hash = 0;
hash += (columnName != null ? columnName.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof TableColumn)) {
return false;
}
TableColumn other = (TableColumn) object;
if ((this.columnName == null && other.columnName != null) || (this.columnName != null && !this.columnName.equals(other.columnName))) {
return false;
}
return true;
}
#Override
public String toString() {
return getColumnName();
}
}
Now we are ready to construct a list of POJO. Use the sample code below to construct get your result as List of POJOs.
public List<TableColumn> findTableColumns(String table) {
List<TableColumn> listTables = new ArrayList<>();
EntityManager em = emf.createEntityManager();
Query q = em.createNativeQuery(TABLE_COLUMNS, TableColumn.class).setParameter(1, table);
listTables = q.getResultList();
em.close();
return listTables;
}
Also, don't forget to add in your POJO class in persistence.xml! It can be easy to overlook if you are used to your IDE managing that file for you.
Had the same kind of problem where I wanted to return a List of POJOs, and really just POJOs (call it DTO if you want) and not #Entity annotated Objects.
class PojoExample {
String name;
#Enumerated(EnumType.STRING)
SomeEnum type;
public PojoExample(String name, SomeEnum type) {
this.name = name;
this.type = type;
}
}
With the following Query:
String query = "SELECT b.name, a.newtype as type FROM tablea a, tableb b where a.tableb_id = b_id";
Query query = getEntityManager().createNativeQuery(query, "PojoExample");
#SuppressWarnings("unchecked")
List<PojoExample> data = query.getResultList();
Creates the PojoExample from the database without the need for an Entity annotation on PojoExample. You can find the method call in the Oracle Docs here.
edit:
As it turns out you have to use #SqlResultSetMapping for this to work, otherwise your query.getResultList() returns a List of Object.
#SqlResultSetMapping(name = "PojoExample",
classes = #ConstructorResult(columns = {
#ColumnResult(name = "name", type = String.class),
#ColumnResult(name = "type", type = String.class)
},
targetClass = PojoExample.class)
)
Just put this anywhere under your #Entity annotation (so in this example either in tablea or tableb because PojoExample has no #Entity annotation)
I have the following tables
Trainingplan
TrainingplanID int(11) AI PK
Trainer int(11)
Client int(11)
validFrom date
validTo date
type int(11)
TrainingplanExercises
trainingplan int(11) PK
exercise int(11) PK
parameter int(11) PK
value varchar(45)
No I have problems connecting them with Hibernate. I did the following:
package beans;
#Entity
#Table(name = "Trainingplan")
public class Training {
private IntegerProperty id;
private ObjectProperty<Person> client;
private ObjectProperty<Person> trainer;
private ObjectProperty<Date> validFrom;
private ObjectProperty<Date> validTo;
private ObjectProperty<TrainingplanType> type;
private List<TrainingplanExercise> exercises;
public Training(int id, Person client, Person trainer, Date validFrom, Date validTo, TrainingplanType type) {
this.id = new SimpleIntegerProperty(id);
this.client = new SimpleObjectProperty<>(client);
this.trainer = new SimpleObjectProperty<>(trainer);
this.validFrom = new SimpleObjectProperty<>(validFrom);
this.validTo = new SimpleObjectProperty<>(validTo);
this.type = new SimpleObjectProperty<>(type);
exercises = FXCollections.observableArrayList();
}
public Training(Person client, Person trainer, Date validFrom, Date validTo, TrainingplanType type){
this(0, client, trainer, validFrom, validTo, type);
}
public Training(){
this(0, null,null,null,null, null);
}
#OneToOne
#JoinColumn(name = "client")
public Person getClient() {
return client.get();
}
public ObjectProperty<Person> clientProperty() {
return client;
}
public void setClient(Person client) {
this.client.set(client);
}
#OneToOne
#JoinColumn(name = "trainer")
public Person getTrainer() {
return trainer.get();
}
public ObjectProperty<Person> trainerProperty() {
return trainer;
}
public void setTrainer(Person trainer) {
this.trainer.set(trainer);
}
#Column
public Date getValidFrom() {
return validFrom.get();
}
public ObjectProperty<Date> validFromProperty() {
return validFrom;
}
public void setValidFrom(Date validFrom) {
this.validFrom.set(validFrom);
}
#Column
public Date getValidTo() {
return validTo.get();
}
public ObjectProperty<Date> validTillProperty() {
return validTo;
}
public void setValidTo(Date validTill) {
this.validTo.set(validTill);
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "TrainingplanID")
public int getId() {
return id.get();
}
public IntegerProperty idProperty() {
return id;
}
public void setId(int id) {
this.id.set(id);
}
#OneToOne
#JoinColumn(name = "type")
public TrainingplanType getType() {
return type.get();
}
public ObjectProperty<TrainingplanType> typeProperty() {
return type;
}
public void setType(TrainingplanType type) {
this.type.set(type);
}
#ManyToMany()
#JoinTable(name="TrainingplanExercises",
joinColumns={#JoinColumn(name="trainingplan")},
inverseJoinColumns={#JoinColumn(name="trainingplan"), #JoinColumn(name="exercise"), #JoinColumn(name="parameter")})
public List<TrainingplanExercise> getExercises() {
return exercises;
}
public void setExercises(List<TrainingplanExercise> exercises) {
this.exercises = exercises;
}
#Override
public String toString() {
return "Training{" +
"id=" + getId() +
", client=" + getClient() +
", trainer=" + getTrainer() +
", validFrom=" + getValidFrom() +
", validTill=" + getValidTo() +
", type=" + getType() +
'}';
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Training training = (Training) o;
return id != null ? id.equals(training.id) : training.id == null;
}
#Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
}
TrainingplanExercise.java
#Entity
#Table(name = "TrainingplanExercises")
#IdClass(TrainingplanExerciseId.class)
public class TrainingplanExercise {
private ObjectProperty<Exercise> exercise;
private ObjectProperty<Training> training;
private ObjectProperty<String> value;
private ObjectProperty<Parameter> parameter;
public TrainingplanExercise(Exercise exercise, Training training, String value, Parameter parameter){
this.exercise = new SimpleObjectProperty<>(exercise);
this.training = new SimpleObjectProperty<>(training);
this.value = new SimpleObjectProperty<>(value);
this.parameter = new SimpleObjectProperty<>(parameter);
}
public TrainingplanExercise(){
this(null,null,null,null);
}
#Id
#OneToOne
#JoinColumn(name = "parameter")
public Parameter getParameter() {
return parameter.get();
}
public ObjectProperty<Parameter> parameterProperty() {
return parameter;
}
public void setParameter(Parameter parameter) {
this.parameter.set(parameter);
}
#Id
#OneToOne
#JoinColumn(name = "exercise")
public Exercise getExercise() {
return exercise.get();
}
public ObjectProperty<Exercise> exerciseProperty() {
return exercise;
}
public void setExercise(Exercise exercise) {
this.exercise.set(exercise);
}
#Id
#OneToOne
#JoinColumn(name = "trainingplan")
public Training getTraining() {
return training.get();
}
public ObjectProperty<Training> trainingProperty() {
return training;
}
public void setTraining(Training training) {
this.training.set(training);
}
#Column(name = "value")
public String getValue(){
return value.get();
}
public ObjectProperty<String> valueProperty() {
return value;
}
public void setValue(String value) {
this.value.set(value);
}
#Override
public String toString() {
return "TrainingplanExercise{" + "exercise=" + exercise + ", training=" + training + ", value=" + value + '}';
}
}
class TrainingplanExerciseId implements Serializable{
protected ObjectProperty<Exercise> exercise;
protected ObjectProperty<Training> training;
protected ObjectProperty<Parameter> parameter;
public TrainingplanExerciseId() {
if(exercise == null)
exercise = new SimpleObjectProperty<>(null);
if(training == null)
training = new SimpleObjectProperty<>(null);
if(parameter == null)
parameter = new SimpleObjectProperty<>(null);
}
public TrainingplanExerciseId(ObjectProperty<Exercise> exercise, ObjectProperty<Training> training, ObjectProperty<Parameter> parameter) {
this.exercise = exercise;
this.training = training;
this.parameter = parameter;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TrainingplanExerciseId that = (TrainingplanExerciseId) o;
if (exercise != null ? !exercise.equals(that.exercise) : that.exercise != null) return false;
if (training != null ? !training.equals(that.training) : that.training != null) return false;
return parameter != null ? parameter.equals(that.parameter) : that.parameter == null;
}
#Override
public int hashCode() {
int result = exercise != null ? exercise.hashCode() : 0;
result = 31 * result + (training != null ? training.hashCode() : 0);
result = 31 * result + (parameter != null ? parameter.hashCode() : 0);
return result;
}
public Exercise getExercise() {
return exercise.get();
}
public ObjectProperty<Exercise> exerciseProperty() {
return exercise;
}
public void setExercise(Exercise exercise) {
this.exercise.set(exercise);
}
public Training getTraining() {
return training.get();
}
public ObjectProperty<Training> trainingProperty() {
return training;
}
public void setTraining(Training training) {
this.training.set(training);
}
public Parameter getParameter() {
return parameter.get();
}
public ObjectProperty<Parameter> parameterProperty() {
return parameter;
}
public void setParameter(Parameter parameter) {
this.parameter.set(parameter);
}
}
Now when I want to save a new Training, I get this error:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'TrainingplanID' in 'field list'
Because of this SQL:
Hibernate: insert into TrainingplanExercises (TrainingplanID, trainingplan, exercise, parameter) values (?, ?, ?, ?)
How do I fix this?
If I change the joinColumn to "trainingplan" I get the error that there are two same columns. If I remove "trainingplan" from the reversed columns, I get an error that one is missing because the foreign constraint requires 3 columns
EDIT:
Try something from the comments. I did try OneToMany/ManyToOne:
#Id
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "trainingplan", nullable = false)
public Training getTraining() {
return training.get();
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "training")
public List<TrainingplanExercise> getExercises() {
return exercises;
}
If I try saving a training to the DB now, it works.
Let's say I want to get a Trainingplan from the database, and add new TrainingplanExercises. I would use this code:
Exercise ex = (Exercise) db.getAll(Exercise.class).get(1);
Training t = (Training) db.getAll(Training.class).get(0);
TrainingplanExercise te = new TrainingplanExercise(ex, t, "asdf", ex.getParameters().get(0));
TrainingplanExercise te1 = new TrainingplanExercise(ex, t, "asdf", ex.getParameters().get(1));
TrainingplanExercise te2 = new TrainingplanExercise(ex, t, "asdf", ex.getParameters().get(2));
TrainingplanExercise te3 = new TrainingplanExercise(ex, t, "asdf", ex.getParameters().get(3));
t.getExercises().clear();
t.getExercises().add(te);
t.getExercises().add(te1);
t.getExercises().add(te2);
t.getExercises().add(te3);
db.updateObj(t);
I get this exception:
Exception in thread "main" org.hibernate.exception.LockTimeoutException: could not execute statement
at org.hibernate.dialect.MySQLDialect$1.convert(MySQLDialect.java:447)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3581)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:104)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:465)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:351)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1258)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at db.Database.updateObj(Database.java:100)
at db.Database.main(Database.java:171)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3835)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3771)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2535)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1911)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2145)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2081)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2066)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 19 more
Okay, look. What you have is a design problem, not really a general problem. First, as I understand it, you want to make a set of unique TrainingplanExercise's. For that, you have this Entity:
#Entity
public class TrainingplanExercise implements Serializable {
#EmbeddedId private TrainingplanExerciseId trainingplanExerciseId;
public TrainingplanExercise() {}
public TrainingplanExercise(TrainingplanExerciseId trainingplanExerciseId) {
this.trainingplanExerciseId = trainingplanExerciseId;
}
... other fields ...
}
The difference between the above Entity and your original Entity is that I have made the ID an EmbeddableId. In order to insure that only unique exercises are put into the TrainingplanExercise's, you have a compositeKey that was defined as a separate class:
#Embeddable
public class TrainingplanExerciseId implements Serializable {
private String exercise;
private String parameter;
public TrainingplanExerciseId() {}
public TrainingplanExerciseId(String exercise, String parameter) {
this.exercise = exercise;
this.parameter = parameter;
}
... getters, setters, hashCode, and equals
}
Here, I have made the class Embeddable so that it can be used as an ID. The way you were trying to declare a compositeKey didn't make any sense; you were trying to declare each individual field in the TrainingplanExercise Entity as an ID, but you can only have one ID.
What is different in this model is that the TrainingplanExerciseId compositeKey does not include a reference back to a TrainingPlan. If you are trying to get a list of TrainingPlan's that use any specific TrainingplanExercise, then you would need a Bidirectional instead of a Unidirectional relationship, but that's a different issue. Otherwise, I don't know why you want to refer back to a TrainingPlan from a TrainingplanExercise. Further, you were putting a reference to the TrainingPlan into the TrainingplanExerciseId compositeKey, which would require the TrainingPlan to be serialized, which really wouldn't work as a unique Id.
Now you can put individual exercises into the table:
public TrainingplanExercise createExercise(String exercise, String parameter) {
TrainingplanExercise trainingplanExercise = new TrainingplanExercise(new TrainingplanExerciseId(exercise, parameter));
em.persist( trainingplanExercise );
return trainingplanExercise;
}
After that, you want to have any number of TrainingPlan's that use the possible TrainingplanExercise's, which you do with this Entity:
#Entity
public class TrainingPlan implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#ManyToMany(fetch=FetchType.EAGER)
private List<TrainingplanExercise> trainingplanExercises = new ArrayList<TrainingplanExercise>();
... getters, setters,
}
You have a ManyToMany relationship because a TrainingPlan refers to many TrainingplanExercise's and a TrainingplanExercise is used by many TrainingPlan's. You don't need any special annotation besides ManyToMany, the JPA provider will create a link table, putting the key from each Entity into a row, like this:
create table TrainingPlan_TrainingplanExercise (
TrainingPlan_id bigint not null,
trainingplanExercises_exercise varchar(255) not null,
trainingplanExercises_parameter varchar(255) not null
);
If you declare it as a OneToMany relationship, then the JPA provider will put an additional constraint on the link table insuring that a TrainingplanExercise cannot be linked to more than one TrainingPlan, so you don't want that. Just for example's sake, this is what the constraint would look like.
alter table TrainingPlan_TrainingplanExercise
add constraint UK_t0ku26ydvjkrme5ycrnlechgi unique (trainingplanExercises_exercise, trainingplanExercises_parameter);
Creating and updating TrainingPlans is straight forward:
public TrainingPlan createTrainingPlan() {
TrainingPlan trainingPlan = new TrainingPlan();
em.persist(trainingPlan);
return trainingPlan;
}
public TrainingPlan updateTrainingPlan(TrainingPlan trainingPlan) {
return em.merge(trainingPlan);
}
Now, you can create TrainingplanExercises and TrainingPlans, and add the exercises to the training plans and update them.
TrainingplanExercise squats20 = trainingService.createExercise("Squats", "20");
TrainingplanExercise lifts10 = trainingService.createExercise("Lifts", "10");
TrainingplanExercise crunches50 = trainingService.createExercise("Crunches", "50");
TrainingPlan trainingPlan = trainingService.createTrainingPlan();
trainingPlan.getTrainingplanExercises().add( squats20 );
trainingPlan.getTrainingplanExercises().add( lifts10 );
trainingService.updateTrainingPlan(trainingPlan);
trainingPlan = trainingService.createTrainingPlan();
trainingPlan.getTrainingplanExercises().add( lifts10 );
trainingPlan.getTrainingplanExercises().add( crunches50 );
trainingService.updateTrainingPlan(trainingPlan);
Also note that your application has the challenge of insuring that only unique TrainingplanExercises are created by users. If a TrainingplanExercise with a duplicate exercise and parameter is attempted to be created you will get a Unique index or primary key violation exception and the transaction will be rolled back.
EDIT: For reading the TrainingPlans, something like this can be used:
public List<TrainingPlan> listTrainingPlans() {
CriteriaQuery<TrainingPlan> criteria = em.getCriteriaBuilder().createQuery(TrainingPlan.class);
criteria.select(criteria.from(TrainingPlan.class));
List<TrainingPlan> trainingPlans = em.createQuery(criteria).getResultList();
return trainingPlans;
}
Note that since the List<TrainingplanExercise> trainingplanExercises is set to FetchType.EAGER this particular query will pull in the entire database. FetchType.EAGER probably isn't a problem for reading a single TrainingPlan, but if you only wanted a list of the TrainingPlan's without getting all of the details, then you would need to work out how FetchType.LAZY should be implemented.
Did you tried using many-to-one mapping instead because it's what you have with a foreign key anyway. You could then try something like:
#Id
#ManyToOne( cascade = {CascadeType.PERSIST}, targetEntity=Trainingplan.class )
#JoinColumn(name = "trainingplan")
public Training getTraining() {}
Currently, I'm using the standard way to map enums with Hibernate, e.g.
#Entity
public class Job {
#Enumerated(EnumType.STRING)
protected State state;
}
public enum State{
NEW,OLD;
}
Now the requirements changed, and I have to create a table State, which contains all the valid values of my enum as String constants. Thus Job must refer to the State table. I don't have to migrate legacy data.
What options do I have to map this with JPA / Hibernate?
Is it possible, to let Hibernate create the State table with values ( 1->"new", 2->"old").
during DDL generation?
in ended up with a solution, which generates the DDL including enum constants and foreign key constraints.
e.g.
#Entity
public enum MyEnum{
#EnumValue
private String name;
#Id
private int id;
}
#Entity
public class MyEntity {
#EnumReference
protected MyEnum myEnum;
}
is sufficient with the following MetadataContributor (/src/main/resources/META-INF/services/org.hibernate.boot.spi.MetadataContributor):
public class EnumConstantsMetadataContributor implements MetadataContributor {
private final static Logger LOG = LoggerFactory.getLogger(EnumConstantsMetadataContributor.class);
private final static List<String> ENABLED_ON = Arrays.asList("validate", "update", "create", "create-drop");
private final static Integer DEFAULT_VARCHAR_SIZE = 255;
private final static Identifier DEFAULT_COLUMN_NAME = Identifier.toIdentifier("enum_constant", false);
#Override
public void contribute(InFlightMetadataCollector metadataCollector, IndexView jandexIndex) {
if (shouldRun(metadataCollector)) {
addEnumsAsTableConstantsAndFkConstraint(metadataCollector);
}
}
private boolean shouldRun(InFlightMetadataCollector metadataCollector) {
StandardServiceRegistry serviceRegistry = metadataCollector.getMetadataBuildingOptions().getServiceRegistry();
ConfigurationService config = serviceRegistry.getService(ConfigurationService.class);
String setting = config.getSetting(AvailableSettings.HBM2DDL_AUTO, String.class, null);
return (setting != null || ENABLED_ON.contains(setting));
}
private void addEnumsAsTableConstantsAndFkConstraint(InFlightMetadataCollector metadataCollector) {
for (PersistentClass persistentClass : metadataCollector.getEntityBindings()) {
Class<?> plainJavaClass = persistentClass.getMappedClass();
if (Enum.class.isAssignableFrom((plainJavaClass))) {
createEnumInsertsAndDbColumns(persistentClass, plainJavaClass, metadataCollector);
}
tryAddFkConstraint(persistentClass, metadataCollector);
}
}
private void tryAddFkConstraint(PersistentClass persistentClass, InFlightMetadataCollector metadataCollector) {
Consumer<Field> createEnumFkConstraintForField = field -> {
String fieldName = field.getName();
PersistentClass targetPersistentClass = metadataCollector.getEntityBinding(field.getType().getCanonicalName());
if (targetPersistentClass == null) {
LOG.error("Target (enum) class must be an #Entity: {}", field.getType().getCanonicalName());
System.exit(1);
}
Property enumReferenceAnnotatedProperty = persistentClass.getProperty(fieldName);
persistentClass.getTable().createForeignKey(null,
Arrays.asList(enumReferenceAnnotatedProperty.getColumnIterator().next()),
targetPersistentClass.getEntityName());
};
Field[] declaredFields = persistentClass.getMappedClass().getDeclaredFields();
of(declaredFields).filter(field -> field.isAnnotationPresent(EnumReference.class)).forEach(
createEnumFkConstraintForField);
}
private void createEnumInsertsAndDbColumns(PersistentClass persistentClass, Class<?> clazz,
InFlightMetadataCollector metadata) {
String tableName = persistentClass.getTable().getName();
Enum<?>[] enumJavaConstants = clazz.asSubclass(Enum.class).getEnumConstants();
ArrayList<String> insertCommandAccumulator = new ArrayList<String>(enumJavaConstants.length);
Optional<Field> enumValueAnnotatedField = of(enumJavaConstants.getClass().getComponentType().getDeclaredFields())
.filter(field -> field.isAnnotationPresent(EnumValue.class)).map(fieldWithEnumValue -> {
fieldWithEnumValue.setAccessible(true);
return fieldWithEnumValue;
}).findAny(); // just none or one is supported
if (enumValueAnnotatedField.isPresent()) {
setMinimalFieldLengthOfExitingColumn(enumValueAnnotatedField.get(), enumJavaConstants, persistentClass);
}
for (int i = 0; i < enumJavaConstants.length; i++) {
Enum<?> it = enumJavaConstants[i];
String constantEnumValue = enumValueAnnotatedField.map(v -> getInstanceValueOfEnumValueAnnotation(it, v))
.orElse(it.name());
if (!enumValueAnnotatedField.isPresent()) {
insertAdditionalColumn(persistentClass, metadata.getDatabase(), enumJavaConstants);
}
insertCommandAccumulator.add(createInsert(tableName, i, constantEnumValue));
}
InitCommand initCommand = new InitCommand(insertCommandAccumulator.toArray(new String[0]));
persistentClass.getTable().addInitCommand(initCommand);
}
private void setMinimalFieldLengthOfExitingColumn(Field field, Enum<?>[] enumJavaConstants,
PersistentClass persistentClass) {
Property property = persistentClass.getProperty(field.getName());
Column column = persistentClass.getTable().getColumn(Identifier.toIdentifier(property.getName()));
Integer maxLengthOfEnums = maxLengthOfEnums(enumJavaConstants,
e -> getInstanceValueOfEnumValueAnnotation(e, field));
column.setLength(maxLengthOfEnums);
}
private String getInstanceValueOfEnumValueAnnotation(Enum<?> myEnum, Field enumValueAnnotatedField) {
try {
return enumValueAnnotatedField.get(myEnum).toString();
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
return null;
}
}
private static Integer maxLengthOfEnums(Enum<?>[] enums, Function<Enum<?>, String> enumConstantValueExtractor) {
return of(enums).map(it -> enumConstantValueExtractor.apply(it).length()).reduce(Math::max)
.orElse(DEFAULT_VARCHAR_SIZE);
};
private void insertAdditionalColumn(PersistentClass persistentClass, Database database, Enum<?>[] enumJavaConstants) {
Integer maxEnumStringLength = maxLengthOfEnums(enumJavaConstants, c -> c.name());
Column column = new Column(DEFAULT_COLUMN_NAME.render(database.getDialect()));
String typeName = database.getDialect().getTypeName(Types.VARCHAR, maxEnumStringLength, 0, 0);
column.setSqlType(typeName);
persistentClass.getTable().addColumn(column);
}
private String createInsert(String tableName, int position, String dbEnumValue) {
return ("insert into " + tableName + " values(" + position + ",\'" + dbEnumValue + "\')");
}
}
Works for MySQL 5.7 and Hibernate 5.
It is not possible to JPA query MyEnum and its consistency between #Enumerated(EnumType.ORDINAL) and getEnumConstants() order is implicitly assumed.
IMHO that does not have too much sense. The values of an enum are static and constant, while the values in a SQL table are dynamic. What if the DB does not contain exactly the values (no more, no less) for such enum?
EDIT: if you are forced to implement it, may something like this work?
public enum State{
int primaryKey;
NEW(0),OLD(1);
public State(int pk) {
primarykey = pk;
}
}
And then join by primary key....
Two entity classes:
#Entity
public class FilesInfo {
#Id
#GeneratedValue
private Integer id;
private String name;
private String url;
#OneToMany(cascade= CascadeType.ALL)
#JoinColumn(name="fileId")
private Collection<FilesShare> filesShared = new ArrayList<FilesShare>();
public Collection<FilesShare> getFilesShared() {
return filesShared;
}
public void setFilesShared(Collection<FilesShare> filesShared) {
this.filesShared = filesShared;
}
the second:
#Entity
public class FilesShare {
#Id
#GeneratedValue
private Integer id;
#Column(name="fileId")
private Integer fileId;
private int userId;
private int owner;
#ManyToOne
#JoinColumn(name="fileId", updatable=false,insertable=false)
private FilesInfo filesInfo;
public FilesInfo getFilesInfo() {
return filesInfo;
}
public void setFilesInfo(FilesInfo filesInfo) {
this.filesInfo = filesInfo;
}
the daoimpl mmethod:
public List<FilesInfo> reqSharedFiles(FilesShare fs) {
session=HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<FilesInfo> filesInfo = null;
filesInfo=(List<FilesInfo>)session.createQuery("from FilesInfo a, FilesShare b where a.id=b.fileId and b.userId=5 and b.owner=1").list();
now i dont understand when hibernate is mapping and returning the object by i am getting this error in action that it cant be casted :
Ljava.lang.Object; cannot be cast to app.domain.FilesInfo
The action
private List<FilesInfo> furls= new ArrayList<FilesInfo>();
furls=upload.reqSharedFiles(fs);
for(FilesInfo s: furls) // ERROR IS SHOWING HERE
{
System.out.println(s.getUrl());
}
Your query does not return a list of FilesInfo, but a list of two-element object arrays where the objects are of type FilesInfo and FilesShare.
You could either rewrite your query so that it only returns a FilesInfo, or attach a ResultTransformer that pulls out the part you're interested in or constructs an object that you can use to get the info you really want.
Your query can result in two diffrent objects, from FilesInfo a, FilesShare b so if it is a FileShare object it cannot be cast to a FilesInfo
see hql from
Thankyou all. Here is what i did after some search.
private List<Object[]> turls=new ArrayList<Object[]>(); //get the list of Object[] from HQL
for(Object[] r : turls)
{
FilesInfo inf =(FilesInfo)r[0];
System.out.println(inf.getUrl());
}
I'm pretty new with hibernate, and I'm trying to transform a JDBC project I have into Hibernate.
I'm using annotations, and I managed to annotate the basic stuff, however, I'm stuck now with the more heavy objects, I don't know how to annotate them.
Here's the Class:
#Entity
#Table(name = "person")
public class Person {
public Person{
}
// THIS WILL BE SOON INJECTED BY SPRING
private static transient PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
private static transient EmailValidator validator = EmailValidator.getInstance();
#Id
#Column(name = "person_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "private_name", nullable = false, length = 20)
private String privateName;
#Column(name = "middle_name", length = 20)
private String middleName;
#Column(name = "family_name", nullable = false, length = 20)
private String familyName;
#Column(name = "age", nullable = false)
private int age;
#Column(name = "address1", nullable = false)
private String address1;
#Column(name = "address2")
private String address2;
//How do I annotate this ? --> Google LIBPHONENUMBER
private PhoneNumber phone;
// How do I annotate this ? --> This is a normal PNG image file.
private File image;
Edit:
The File was previously mapped as a BLOB.
The PhoneNumber was previously persisted as String, and was transformed using the PhoneNumber constructor to Phonenumber.
The other comments about using #Lob are correct for the File type. It is also correct that if you can change the schema to not save the file data in the DB, then you probably should.
To map your PhoneNumber class to a database field, you're going to need to use a Hibernate custom UserType. It basically tells Hibernate HOW to do the object<-->db mapping for classes that it doesn't already know about. Telling the PhoneNumber field in Person to use a custom user type is easy:
#Type(type = PhoneNumberType.CLASS_NAME)
#Column
private PhoneNumber phone;
This assumes a very simple one-column storage of the phone number.
To write PhoneNumberType, you'll need to implement UserType. It looks overwhelming, with the assemble/disassemble/deepCopy, but the main part you care about is nullSetGet/Set, returnedClass and sqlTypes. You'll end up with some code like this inside your custom type:
#Override
public Class<?> returnedClass() {
return PhoneNumber.class;
}
#Override
public int[] sqlTypes() {
return new int[] { Types.VARCHAR };
}
#Override
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
final String value = rs.getString(names[0]);
return /* PhoneNumber instance created from string. */
}
#Override
public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.VARBINARY);
return;
}
st.setString(index, ((PhoneNumber) value).toString());
}
You can find plenty of information about how to implement the other methods via google, stackoverflow and the hibernate javadocs. It isn't that hard to do.
UPDATE: Multi-column user type
Implement CompositeUserType instead of just UserType. There are a few method changes that you care about. First you'll want to define the multiple property names and types:
public String[] getPropertyNames() {
return new String[] { "number", "code" };
}
public Type[] getPropertyTypes() {
return new Type[] { StandardBasicTypes.STRING,
StandardBasicTypes.STRING };
}
There's also getPropertyValue/setPropertyValue to implement. Your nullSafeXxxx implementations would change to read and write two properties instead of one:
#Override
public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
// Access column in order defined in getPropertyNames()
final String number = rs.getString(names[0]);
final String code = rs.getString(names[1]);
return /* PhoneNumber instance created from number and country code. */
}
Personally, I'd store only the filename in the object, and keep the file on the filesystem, where files belong.
Otherwise, map it as a Hibernate blob (#Lob) and you'd want it to be a byte array (would translate to a blob).
IMO this usually creates more trouble than it's worth, but that depends partially on the DB, driver revision, etc.
Just create a Hibernate UserType for PhoneNumber
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import org.apache.commons.lang.ObjectUtils;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.type.StringRepresentableType;
import org.hibernate.usertype.UserType;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import com.tg.util.TGPhoneUtils;
public class PhoneNumberUserType implements UserType, StringRepresentableType<PhoneNumber>, Serializable {
private static final long serialVersionUID = -364436436346432L;
#Override
public boolean equals(Object x, Object y) throws HibernateException {
return ObjectUtils.equals(x, y);
}
#Override
public int hashCode(Object object) throws HibernateException {
return object.hashCode();
}
#Override
public Object deepCopy(Object value) throws HibernateException {
return value;
}
#Override
public boolean isMutable() {
return false;
}
#Override
public Serializable disassemble(Object value) throws HibernateException {
return (Serializable) value;
}
#Override
public Object assemble(Serializable cached, Object value) throws HibernateException {
return cached;
}
#Override
public Object replace(Object original, Object target, Object owner) throws HibernateException {
return original;
}
#Override
public String toString(PhoneNumber value) throws HibernateException {
return value.toString();
}
#Override
public Class<?> returnedClass() {
return PhoneNumber.class;
}
#Override
public int[] sqlTypes() {
return new int[] { Types.VARCHAR };
}
#Override
public PhoneNumber fromStringValue(String number) throws HibernateException {
try {
return PhoneNumberUtil.getInstance().parse(number, "US");
} catch (NumberParseException e) {
throw new HibernateException(e);
}
}
#Override
public Object nullSafeGet(ResultSet rs, String[] names, SessionImplementor arg2, Object owner) throws HibernateException, SQLException {
final String number = rs.getString(names[0]);
if (number == null) {
return null;
}
return TGPhoneUtils.parsePhoneNumber(number);
}
#Override
public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor si) throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, Types.VARCHAR);
return;
}
st.setString(index, TGPhoneUtils.formatPhoneNumber((PhoneNumber)value));
}
}
and then here is the helper class
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
public class TGPhoneUtils {
public static PhoneNumber parsePhoneNumber(String phoneNum) {
if (phoneNum == null) {
return null;
}
try {
return PhoneNumberUtil.getInstance().parse(phoneNum, "US");
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String formatPhoneNumber(PhoneNumber phoneNum) {
if (phoneNum == null) {
return null;
}
return PhoneNumberUtil.getInstance().format(phoneNum, PhoneNumberFormat.E164);
}
}
You can annotate PhoneNumber like this:
#ManyToOne
#JoinColumn(name = "PHONE_NUMBER")
private PhoneNumber phone;
Assuming that the column PHONE_NUMBER exists and maps to the id of a phone number. The class PhoneNumber will also need to be annotated. This assumes that you want to maybe share a phone number among different entities (Many to one).
Regarding file, you probably need to decide if you want to actually store the file data in the db (normally not a good idea). Otherwise you could just store a String with a path to file.