I am facing an issue with entitymanger that it inserts data instead of updating. Here is my entity and all code snippet that we are using. I have checked hibernate logs as well I see it creates an insert operation rather than an update.
Maven dependencies
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.2.7.SP1-redhat-3</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7.redhat-4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.7.SP1-redhat-3</version>
<scope>test</scope>
</dependency>
Code Snippet.
jpaTableDao.update(jpaTable1) // calling abstract update method
public interface ITable extends Src {
public String getPrefix();
public void setPrefix(String channelPrefix);
.......
}
public interface Src extends Entity, TimeStamp {
String getName();
void setName(String name);
..........
public String getType();
public void setType(String type);
}
public interface Entity {
Serializable getId();
void setId(Serializable id);
}
@Entity(name = "Src")
@IdClass(JpaSrcKey.class)
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class JpaSrc extends JpaTimeStamp implements Src {
@Id
@GenericGenerator(name = "src_id_generator", strategy = "com.demo.id.generator.SrcIdGenerator")
@GeneratedValue(generator = "src_id_generator")
protected Integer id;
@Id
@Column(length = 14)
protected String type;
}
@Entity(name = "Table1")
@org.hibernate.annotations.Table(appliesTo = "Table1", indexes = {
@Index(name = "A_dobject_Idx", columnNames = { "dobject_id" }) })
public class JpaTable1 extends JpaSrc implements ITable {
{
type = "Table1";
}
@Column(length = 14)
private String code;
}
public interface SrcKey extends Serializable {
}
public class JpaSrcKey implements Serializable, SrcKey {
private static final long serialVersionUID = 5844060606871925217L;
private Serializable id;
private String type;
public JpaSrcKey() {
}
public JpaSrcKey(Serializable id, String type) {
this.type = type;
Validate.notNull(id);
this.id = id;
}
...
}
public class JpaTableDao extends AbstractIamDao<ITable, SrcKey> implements ITableDao<SrcKey> {
protected JpaTableDao() {
super(JpaTable1.class);
}
}
public abstract class AbstractJpaDao<T extends Entity, Id extends Serializable> implements Dao<T, Id> {
private EntityManager entityManager;
.........
public T update(final T entity) {
final T result;
if (entityManager.contains(entity)) {
result = entity;
} else {
result = entityManager.merge(entity);
}
return result;
}
}