I'm trying to use JPA to generate IDs from sequences in my database (Oracle 9i)
From what I found here and there, here is the group of annotations I've set on my ID variable :
#Id
#SequenceGenerator(name="PROCEDURENORMALE_SEQ_GEN", sequenceName = "PROCEDURENORMALE_SEQ")
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "PROCEDURENORMALE_SEQ_GEN")
#Column(name = "IDPROCEDURENORMALE", unique = true, nullable = false, precision = 10, scale = 0)
private long idProcedureNormale;
However, whenever I create a new object, this id is always set to 0, and because of that I can't persist data. I've tried to change the strategy from GenerationType.SEQUENCE to GenerationType.AUTO, nothing changed. For this specific table, Sequence number is supposed to be around 8300.
Where did I go wrong ?
I actually solved my issue, that happened not to be directly related with what I exposed.
This object I was trying to persist is part of a relatively complex object, and in the parent object I didn't add a CascadeType to the JPA mapping annotation :
#OneToMany(fetch = FetchType.LAZY, mappedBy = "dossier")
private Set<Procedurenormale> proceduresNormales = new HashSet<>(0);
Changing this annotation to the following solved the issue :
#OneToMany(fetch = FetchType.LAZY, mappedBy = "dossier", cascade = CascadeType.ALL)
private Set<Procedurenormale> proceduresNormales = new HashSet<>(0);
Related
class B{
#Any(metaColumn = #Column(name = "ITEM_TYPE"))
#AnyMetaDef(idType = "long", metaType = "string",
metaValues = {
#MetaValue(targetEntity = A.class, value = "A")
})
#Cascade( { org.hibernate.annotations.CascadeType.ALL})
#JoinColumn(name = "ITEM_ID")
private A a;
...
...
}
I'm trying to Join table A and table B where B.item_type ='A' is constant and B.item_id= A.id.
It is throwing me
Caused by: org.hibernate.MappingException: Foreign key (FKi1uuph2wrvxtx66s7n7i1s09a:B [item_type,item_id])) must have same number of columns as the referenced primary key (A [id])
Any help on How shall i map this using spring jpa and hibernate?
Your question is not to clear but below may help
Join table A and table B where B.item_type ='A' is constant and B.item_id= A.id.
1) B.item_type = 'A' : Create A enum and pass it while querying
2) B.item_id=A.id :
lets says it is one to many relation.
Class B{
#OneToMany
#Cascade(org.hibernate.annotations.CascadeType.DETACH)
#JoinColumns(#JoinColumn(name = "id", referencedColumnName = "item_id", insertable = false, updatable = false))
List<A> retunedList;
}
In case when it will be one to one, Change Annotaion to #onetoOne and make return type A instead of list.
I was able to fix this by a alternate approach where I made the associated entity as #Transient and then I saved that transient entity on #PostPersist call from parent entity by adding an EntityListener class.
I have an Entity such as:
#Entity
class Brand {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(nullable = false, columnDefinition = "BIGINT")
private Long id;
#NotNull(message = NOT_NULL_CODE)
#Size(min = 5, max = 150, message = SIZE_CODE)
#Column(nullable = false, length = 150)
private String name;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "organization_id", nullable = false)
#JsonBackReference("organization-brands")
private Organization organization;
// getters and setters
}
My repository has the following defined:
Page<Brand> findAllByOrganization(Organization organization, Pageable pageable);
This results in the following query:
select
brand0_.id as id1_1_,
brand0_.name as name2_1_,
brand0_.organization_id as organiza3_1_
from
brand brand0_
left outer join
organization organizati1_
on brand0_.organization_id=organizati1_.id
where
organizati1_.id=? limit ?
I'm wondering why there is a left outer join created? I thought maybe it was because the organization_id was part of the select so I created a DTO Projection that only included the name and id columns, but that still included the left outer join. I found this bug report filed but there's been zero movement on it.
The reason this is concerning for me is because the left outer join adds, on average, 200ms to the query. I haven't done any benchmarking to determine if this grows exponentially with more rows of data or not. But with my current dataset, it's 200ms. Yikes.
This is most likely related to:
http://stackoverflow.com/a/17987718/1356423
From the presence of your nullable = false on the column definition it looks like the relationship is non-optional so try annotating as #ManyToOne(fetch = FetchType.LAZY, optional = false)
Without theoptional = false Hibernate has to check the association table to see whether to set either a proxy or null for the associated Organisation: hence the join.
assuming Organization class PK is named as id
then
Page<Brand> findAllByOrganizationId(String organizationId, Pageable pageable);
should do what you want
I'm trying to query for a list of entities (MyOrders) that have mappings to a few simple sub-entities: each MyOrder is associated with exactly one Store, zero or more Transactions, and at most one Tender. The generated SELECT appears correct - it retrieves all the columns from all four joined tables - but afterwards, two more SELECTs are executed for each MyOrder, one for Transactions and one for Tender.
I'm using QueryDSL 4.1.3, Spring Data 1.12, JPA 2.1, and Hibernate 5.2.
In QueryDSL, my query is:
... = new JPAQuery<MyOrder>(entityManager)
.from(qMyOrder)
.where(predicates)
.join(qMyOrder.store).fetchJoin()
.leftJoin(qMyOrder.transactions).fetchJoin()
.leftJoin(qMyOrder.tender).fetchJoin()
.orderBy(qMyOrder.orderId.asc())
.transform(GroupBy
.groupBy(qMyOrder.orderId)
.list(qMyOrder));
which is executed as:
SELECT myorder0_.ord_id AS col_0_0_,
myorder0_.ord_id AS col_1_0_,
store1_.sto_id AS sto_id1_56_1_, -- store's PK
transactions3_.trn_no AS trn_no1_61_2_, -- transaction's PK
tender4_.tender_id AS pos_trn_1_48_3_, -- tender's PK
myorder0_.ord_id AS ord_id1_39_0_,
myorder0_.app_name AS app_name3_39_0_, -- {app_name, ord_num} is unique
myorder0_.ord_num AS ord_num8_39_0_,
myorder0_.sto_id AS sto_id17_39_0_,
store1_.division_num AS div_nu2_56_1_,
store1_.store_num AS store_nu29_56_1_,
transactions3_.trn_cd AS trn_cd18_61_2_,
tx2myOrder2_.app_name AS app_name3_7_0__, -- join table
tx2myOrder2_.ord_no AS ord_no6_7_0__,
tx2myOrder2_.trn_no AS trn_no1_7_0__,
tender4_.app_name AS app_name2_48_3_,
tender4_.ord_num AS ord_num5_48_3_,
tender4_.tender_cd AS tender_cd_7_48_3_,
FROM data.MY_ORDER myorder0_
INNER JOIN data.STORE store1_ ON myorder0_.sto_id=store1_.sto_id
LEFT OUTER JOIN data.TX_to_MY_ORDER tx2myOrder2_
ON myorder0_.app_name=tx2myOrder2_.app_name
AND myorder0_.ord_num=tx2myOrder2_.ord_no
LEFT OUTER JOIN data.TRANSACTION transactions3_ ON tx2myOrder2_.trn_no=transactions3_.trn_no
LEFT OUTER JOIN data.TENDER tender4_
ON myorder0_.app_name=tender4_.app_name
AND myorder0_.ord_num=tender4_.ord_num
ORDER BY myorder0_.ord_id ASC
which is pretty much what I'd expect. (I cut out most of the data columns for brevity, but everything I need is SELECTed.)
When querying an in-memory H2 database (set up with Spring's #DataJpaTest annotation), after this query executes, a second query is made against the Tender table, but not Transaction. When querying a MS SQL database, the initial query is identical, but additional queries happen against both Tender and Transaction. Neither makes additional calls to load Store.
All the sources I've found suggest that the .fetchJoin() should be sufficient (such as Opinionated JPA with Query DSL; scroll up a few lines from the anchor) and indeed if I remove them, the initial query only selects columns from MY_ORDER. So it appears that .fetchJoin() does force generation of a query that fetches all the side tables in one go, but for some reason that extra information isn't being used. What's really weird is that I do see the Transaction data being attached in my H2 quasi-unit test without a second query (if and only if I use .fetchJoin() ) but not when using MS SQL.
I've tried annotating the entity mappings with #Fetch(FetchMode.JOIN), but the secondary queries still fire. I suspect there might be a solution involving extending CrudRepository<>, but I've had no success getting even the initial query correct there.
My primary entity mapping, using Lombok's #Data annotations, other fields trimmed out for brevity. (Store, Transaction, and Tender all have an #Id a handful of simple numeric and string field-column mappings, no #Formulas or #OneToOnes or anything else.)
#Data
#NoArgsConstructor
#Entity
#Immutable
#Table(name = "MY_ORDER", schema = "Data")
public class MyOrder implements Serializable {
#Id
#Column(name = "ORD_ID")
private Integer orderId;
#NonNull
#Column(name = "APP_NAME")
private String appName;
#NonNull
#Column(name = "ORD_NUM")
private String orderNumber;
#ManyToOne
#JoinColumn(name = "STO_ID")
private Store store;
#OneToOne
#JoinColumns({
#JoinColumn(name = "APP_NAME", referencedColumnName = "APP_NAME", insertable = false, updatable = false),
#JoinColumn(name = "ORD_NUM", referencedColumnName = "ORD_NUM", insertable = false, updatable = false)})
#org.hibernate.annotations.ForeignKey(name = "none")
private Tender tender;
#OneToMany
#JoinTable(
name = "TX_to_MY_ORDER", schema = "Data",
joinColumns = { // note X_to_MY_ORDER.ORD_NO vs. ORD_NUM
#JoinColumn(name = "APP_NAM", referencedColumnName = "APP_NAM", insertable = false, updatable = false),
#JoinColumn(name = "ORD_NO", referencedColumnName = "ORD_NUM", insertable = false, updatable = false)},
inverseJoinColumns = {#JoinColumn(name = "TRN_NO", insertable = false, updatable = false)})
#org.hibernate.annotations.ForeignKey(name = "none")
private Set<Transaction> transactions;
/**
* Because APP_NAM and ORD_NUM are not foreign keys to TX_TO_MY_ORDER (and they shouldn't be),
* Hibernate 5.x saves this toString() as the 'owner' key of the transactions collection such that
* it then appears in the transactions collection's own .toString(). Lombok's default generated
* toString() includes this.getTransactions().toString(), which causes an infinite recursive loop.
* #return a string that is unique per order
*/
#Override
public String toString() {
// use appName + orderNumber since, as they are the columns used in the join, they must (?) have
// already been set when attaching the transactions - primary key sometimes isn't set yet.
return this.appName + "\00" + this.orderNumber;
}
}
My question is: why am I getting redundant SELECTs, and how can I not do that?
I'm a little too late on the answer, but today the same problem happened to me. This response might not help you, but at least it would save someone the headache we went through.
The problem is on the relations between the entities, not in the query. I tried with QueryDSL, JPQL, and even native SQL but the problem was always the same.
The solution was to trick JPA into believing that the relations were there via annotating the child classes with #Id on those joined fields.
Basically you'll need to set Tender's id like this and use it from MyOrder like if it was a normal relationship.
public class Tender {
#EmbeddedId
private TenderId id;
}
#Embeddable
public class TenderId {
#Column(name = "APP_NAME")
private String appName;
#Column(name = "ORD_NUM")
private String orderNumber;
}
The same would go for the Transaction entity.
I have found that hibernate (or mariadb) JPA does not seem to work with 0 values in a foreign key.
I have a parent class
class Parent {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "PARENT_ID", unique = true, nullable = false)
private Integer parentId;
}
And a child class
class Child {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "CHILD_ID", unique = true, nullable = false)
private Integer childId;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "PARENT_ID", nullable = false)
private Parent parent;
}
So we have 2 rows in parent. parent_id=0 and parent_id=1
My problem is that I get an error when attempting to use parent with ID 0. i.e. This code
Parent p = entityManager.find(Parent.class, new Integer(0));
Child c = new Child();
c.setParent(p);
entityManager.persist(c);
Will fail with the error:
java.lang.IllegalStateException:
org.hibernate.TransientPropertyValueException: Not-null property
references a transient value - transient instance must be saved before
current operation : com.whatever.Child.parent -> com.whatever.Parent
But the following works fine:
Parent p = entityManager.find(Parent.class, new Integer(1));
Child c = new Child();
c.setParent(p);
entityManager.persist(c);
So I assume the PARENT_ID=0 somehow confusing JPA into thinking it is not a valid parent object.
Or is this actually a mariadb issue? Related to the fact that you have to change a session setting in order to insert 0's into AUTO_INCREMENT columns.
Is there any config or annotation I can do to make this work. Unfortunately we are putting JPA code on an existing system, so changing the PARENT_ID values is not a trivial task. (and everybody hates data conversion).
Any tips very much appreciated.
MariaDB/MySQL handle AUTO_INCREMENT thus: Numbers are 1 or greater; 0 is a valid sequence number. If JPA cannot live with those (and some other) limitations, JPA is broken. (Sorry, but I get irritated with 3rd party software that makes life difficult for MySQL users.)
I have an entity in Java and I would like Hibernate to create a foreign key from an Integer field (since I don't have an object reference):
#Entity
public class Invoice {
...
#Column(nullable = true)
private Integer generatedBy;
...
I think I'd like to do something like this with an attribute:
#ForeignKey(name="FK_Invoice_GeneratedBy", references="UserTable.UserId")
#Column(nullable = true)
private Integer generatedBy;
What is the best way to achieve this? I would preferably not have to maintain these relationships in a separate file (if possible).
There doesn't seem to be a solution to this, thus accepting this as an answer.
There is a way to do it, but it is not very nice...
You can have your integer attribute, AND an object attribute mapped this way:
#Column(ame = "GENERATED_BY", nullable = true)
private Integer generatedBy;
#ForeignKey(name="FK_Invoice_GeneratedBy")
#JoinColumn(name = "GENERATED_BY", nullable = false, updatable = false, insertable = false)
private User generatedByUser;
You may keep no external access to your generatedByUser field, it will only show hibernate that there is a relationship. You can set the Integer field at will, when you load this object from DB later you'll have your user reference.
Again, not very pretty, but can be useful sometimes.