How can we assign a field of user table say id that is primary key, to another table as a primary key? using hibernate - sql

See I dont want any mapping but what I want is just a simple thing that is....
I have two Entity
Tasks(taskid,taskname.....,userId)
User_Credentials(userId,password)
So What I want is userId of User Credentials used as a foreign key in Task table.
So when I fire an api to save the task I have to also pass the all details of user Credentials That I dont want.
{
"taskName": "Test",
"taskStatus": "Open",
"taskDueDate": "2022-04-15",
"taskCreatedDate": "2022-04-10",
"taskDescription": "Demo",
"taskPriority": "High",
"isTaskActive": "Yes",
"userCredentials":{
"associateId":"108",
"password":"something#9122"
}
}
What I want is
{
"taskName": "Test",
"taskStatus": "Open",
"taskDueDate": "2022-04-15",
"taskCreatedDate": "2022-04-10",
"taskDescription": "Demo",
"taskPriority": "High",
"isTaskActive": "Yes",
"userCredentials":"108"
}
That I want to post and if userCredentials id 108 is not in User Credentials Table so it pop up an error and if it is there it will save just like a foreign key concept.
So please tell me ho to do that.

You can use ElementCollection to achieve this.
In Tasks entity
#Id
#Column(name = "task_id")
private Integer id;
#ElementCollection
#CollectionTable(name = "task_user", joinColumns = #JoinColumn(name = "task_id", nullable = false))
#Column(name = "user_id", nullable = false)
private List<Integer> userCredentials;
In UserCredentials entity
#Id
#Column(name = "user_id")
private Integer id;
UserCredentials is an independent entity with no mapping with Tasks. You will now be able to pass UserCredentials like this userCredentials: [108] in the Tasks.
Add the following in your application.yml to generate the create.sql script with ddl commands for all the entities. ddl-auto: validate will restrict hibernate from creating the tables on its own.
spring:
jpa:
hibernate:
ddl-auto: validate
properties:
javax:
persistence:
schema-generation:
create-source: metadata
scripts:
action: create
create-target: create.sql
generate-ddl: true
The following is the ddl command to add foreign key constraints for tables user_credentials and tasks. Execute it alongwith the create.sql in any DB client.
CREATE TABLE "task_user"
( "user_id" integer ,
"task_id" integer,
PRIMARY KEY ("user_id","task_id"),
CONSTRAINT user_id_fkey
FOREIGN KEY ("user_id") REFERENCES "user_credentials" ("user_id"),
CONSTRAINT task_id_fkey
FOREIGN KEY ("task_id") REFERENCES "tasks" ("task_id")
);
Note: The create.sql already has a task_user create command but it needs to be replaced with the above command.

Related

JPA/Hibernate overlapping PK and FK Columns

we're using Postgres and JPA/Hibernate to import a lot of data on a biweekly basis (~50-100M rows per import). We're trying to partition our tables per import, which has us running into some Hibernate PK/FK column mapping problems. The setup is essentially this on the SQL side
CREATE TABLE row (
import_timestamp timestamp,
id uuid,
PRIMARY KEY (import_timestamp, id)
) PARTITION BY LIST (import_timestamp);
CREATE TABLE row_detail (
import_timestamp timestamp,
id uuid,
row_id uuid,
PRIMARY KEY(import_timestamp, id),
CONSTRAINT row_detail_row_fk FOREIGN KEY (row_id, import_timestamp) REFERENCES row (id, import_timestamp)
) PARTITION BY LIST (import_timestamp);
and this on the Java side:
#Entity(name = "row")
public class RowEntity {
#EmbeddedId
private PartitionedId id;
#OneToMany(cascade = ALL, mappedBy = "row")
private List<RowDetailEntity> details;
}
#Entity(name = "row_detail")
public class RowDetailEntity {
#EmbeddedId
private PartitionedId id;
#ManyToOne
#JoinColumns({
#JoinColumn(name = "row_id", referencedColumnName = "id"),
#JoinColumn(name = "importTimestamp", referencedColumnName = "importTimestamp")
})
private RowEntity row;
}
#Embeddable
public class PartitionedId implements Serializable {
private Instant importTimestamp;
private UUID id;
}
Hibernate then complains on boot that:
column: import_timestamp (should be mapped with insert="false" update="false")
I can silence that error by doing as it says, but that makes little sense, because I am forced to set insertable=false and updatable=false for both #JoinColumn()s, which would mean row_id isn't populated on insert.
I could go the #MapsId route, but only if I give the row_detail table a PK that includes all 3 properties (import_timestamp, id, row_id), and I don't really want or need that.
So the question is, how do I get Hibernate to understand my overlapping, but not entirely nested PK/FK?

Spring Data JPA does not persist the oneToMany list

I am creating a new project and using Spring Data JPA to create some REST endpoints.
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
I am able to put and persist to my primary class (customer), which works as long as the json file does not have any oneToMany data. However, when posting to customer, if there is oneToMany data I am getting errors.
The errors relate to the foreign key being null when trying to persist. I am not sure how Spring Data JPA should be using the annotation to let hibernate know what the value of the foreign key should be.
I have looked at numerous bi-directional OneToMany examples, as well as examples for creating foreign keys and have tried a number of modifications without success.
I also tried to use the spring.jpa.hibernate.ddl-auto=update to help create and update the database schema without any luck.
The customer
#Entity
#Table(name="customer")
#EntityListeners(AuditingEntityListener.class)
public class Customer extends Auditable<String> {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="first_name")
private String firstName;
#Column(name="last_name")
private String lastName;
#OneToMany(fetch=FetchType.LAZY, mappedBy="customer", cascade={CascadeType.ALL})
private List<EmailAddress> emailAddresses;
.......
The emails
#Table(name="email_address")
#EntityListeners(AuditingEntityListener.class)
public class EmailAddress extends Auditable<String> {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="email_type")
private byte emailType;
#Column(name="email")
private String email;
#ManyToOne(fetch=FetchType.LAZY, cascade={CascadeType.ALL})
#JoinColumn(name="customer_id")
#JsonIgnore
private Customer customer;
.....
The postman json test
{
"id": 1,
"firstName": "Bobby",
"lastName": "Smith",
"emailAddresses": [
{
"id": 1,
"emailType": 1,
"email": "bobby#bobby.com",
},
{
"id": 2,
"emailType": 1,
"email": "bobby#gmail.com",
}
]
}
BTW, I have confirmed that within the customer controller, that the emails are included in the request body of customer.
The customer controller
#PutMapping("/customers")
public Customer updateCustomer(#RequestBody Customer theCustomer) {
System.out.println("****email count "+theCustomer.getEmailAddresses().size());
for(EmailAddress index: theCustomer.getEmailAddresses()) {
System.out.println(index.toString());
}
customerService.save(theCustomer);
return theCustomer;
}
The customer service
#Override
public void save(Customer theCustomer) {
//Validate the input
if(theCustomer == null) {
throw new CustomerNotFoundException("Did not find the Customer, was null...");
}
customerRepository.save(theCustomer);
}
MySQL Script
--
-- Table structure for table `customer`
--
DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`first_name` varchar(24) COLLATE utf8_bin NOT NULL,
`last_name` varchar(24) COLLATE utf8_bin NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='Primary Customer Table';
--
-- Table structure for table `email_address`
--
DROP TABLE IF EXISTS `email_address`;
CREATE TABLE `email_address` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email_type` tinyint(4) unsigned NOT NULL COMMENT 'email type',
`email` varchar(128) COLLATE utf8_bin NOT NULL COMMENT 'email address',
`customer_id` int(11) NOT NULL COMMENT 'foreign key',
INDEX par_ind (customer_id),
PRIMARY KEY (`id`),
UNIQUE KEY `email` (`email`),
KEY FK_EMAIL_CUSTOMER_idx (customer_id),
CONSTRAINT FK_EMAIL_CUSTOMER FOREIGN KEY (customer_id) REFERENCES customer (id) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='email addresses';
Postman Complaint
{
"status": 400,
"message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
"timeStamp": 1566840491483
}
Console Complaint
****email count 2
EmailAddress [id=1, type=1, email=bobby#bobby.com]
EmailAddress [id=2, type=1, email=bobby#gmail.com]
2019-08-28 17:33:07.625 WARN 8669 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1048, SQLState: 23000
2019-08-28 17:33:07.626 ERROR 8669 --- [nio-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : Column 'customer_id' cannot be null
2019-08-28 17:33:07.629 ERROR 8669 --- [nio-8080-exec-2] o.h.i.ExceptionMapperStandardImpl : HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
2019-08-28 17:33:07.735 WARN 8669 --- [nio-8080-exec-2] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement]
Therefore, with a post or put, I am not sure why the Spring Data JPA save does not satisfy the foreign key constraint for entities with oneToMany relationships. I am guessing it is either some missing annotations or something wrong with my sql script. Not sure why the update data does not persist to the email_address table. Does the emailAddress entity require some type of getter/setter for customer_id?
public class Customer extends Auditable<String> {
#OneToMany(fetch=FetchType.LAZY, mappedBy="customer", cascade={CascadeType.ALL})
private List<EmailAddress> emailAddresses;
}
public class EmailAddress extends Auditable<String> {
#ManyToOne(fetch=FetchType.LAZY, cascade={CascadeType.ALL})
#JoinColumn(name="customer_id")
private Customer customer;
}
The mappedBy here means that the relationship between Customer and EmailAddress (i.e. the value of customer_id in customer table ) are determined by EmailAdress#cutomer but not Customer#emailAdresses.
What you are trying to show it just the content of Customer#emailAddress which will be ignored by Hibernate when deciding which DB values to be updated/inserted for this relationship. So you have to make sure EmailAddress#customer are set correctly.
For example , you can have the following method to add an email address to a Customer
public class Customer {
#OneToMany(fetch=FetchType.LAZY, mappedBy="customer", cascade={CascadeType.ALL})
private List<EmailAddress> emailAddresses;
public void addEmailAddress(EmailAddress email){
//As said Hibernate will ignore it when persist this relationship.
//Add it mainly for the consistency of this relationship for both side in the Java instance
this.emailAddresses.add(email);
email.setCustomer(this);
}
}
And always call addEmailAddress() to add an email for a customer. You can apply the same idea for updating an email address for a customer.

Spring Data JPA persistence - Could not commit JPA transaction - ORA-00001: unique constraint violated

I am trying to save an entity that has a many-to-many association to another entity and cascade the persistence to the associated entity and create the association using spring data jpa repository.
I can insert the parent entity_a which contains a set of entity_b using entityARepository.save(entityA). Spring jpa is taking care of all the inserts needed in the transaction. All the entity_b's get inserted, entity_a's get inserted and the join table in the middle has the association inserted as well. If I update the same entity_a with a new value in, say timestamp column, the same entityARepository.save(entityA) handles this and does a corresponding update.
The problem happens when there already exists entity_b (which has an association between some entity_a) and I try to insert a new entity_a with the same entity_b. It is many to many so this is how the data model is supposed to be. But instead of updating the existing entity_b during this entityA save() transaction, it tries to do inserts on entity_b and a constraint violation exception on the primary key is thrown.
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (USER1.SYS_C0013494) violated
Error Code: 1
Call: INSERT INTO ENTITY_B (ID, NAME, VALUE, TIME_STAMP) VALUES (?, ?, ?, ?)
bind => [4 parameters bound]
Query: InsertObjectQuery(EntityB [name=shape, value=circle])
The problem is that spring doesn't have update(). It only has save which should handle update if it receives the same primary key. It's not doing that when a new entity_a is saved and has a collection of entity_b, if any entity_b exists, the whole transaction is failing sure to primary key constraint violation of entity_b.
public class EntityA {
#Id
#SequenceGenerator( name = "EntityASeq", sequenceName = "SQ_ENTITY_A", allocationSize = 1, initialValue = 1 )
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "EntityASeq")
#Column(name = "ID")
private Integer id;
#ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.LAZY)
#JoinTable(name = "MY_JOINED_TABLE",
joinColumns = {
#JoinColumn(name = "a_id", referencedColumnName = "ID")},
inverseJoinColumns = {
#JoinColumn(name = "b_id", referencedColumnName = "ID")})
private Set<EntityB> attributes;
// These three columns below have a unique constraint together.
#Column(name = "name")
private String name;
#Column(name = "tenant")
private String tenant;
#Column(name = "type")
private String type;
#Column(name = "timestamp")
private Timestamp timestamp;
}
public class EntityB {
#Id
#SequenceGenerator( name = "EntityBSeq", sequenceName = "SQ_ENTITY_B", allocationSize = 1, initialValue = 1 )
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "EntityBSeq")
#Column(name = "ID")
private Integer id;
#ManyToMany(mappedBy = "attributes")
private Set<EntityA> aSet;
// These two columns below have a unique constraint together.
#Column(name = "name")
private String name;
#Column(name = "value")
private String value;
#Column(name = "timestamp")
private Timestamp timestamp;
}
The id for each is generated by default. I also have a unique constraint on a few columns, which means if an EntityB has the same name/value as an existing one in the database, I want to just update the timestamp. That works if entity_a is already in the table and it has the same entity_b's. A and B's timestamp are updated and no error when I persist with entityARepository.save(entityA). (I do some checking on the db with findOne because the id is auto generated an not known. So if a name/value exist, I don't try to insert with a new id, I use the same one in the db and it works (similarly with entity_atenant/name/type.
It also works when I persist an existing entity_a with updated entity_b's. So if a new entity_b is associated with entity_a (that exists as an association with a different entity_a), etc, that works and the persistence is working.
The issue again, is just on INSERT of entityA via repo.save() when some entity_b
s already exist for other associations. It should be doing:
INSERT INTO entity_a ...
UPDATE entity_b ...
INSERT INTO MY_JOINED_TABLE ...
But it seems like it's doing
INSERT INTO entity_a ...
INSERT INTO entity_b ... -- fails because primary key constraint fails
INSERT INTO MY_JOINED_TABLE ...
EDIT: I tried removing CascadeType.PERSIST but I get an error saying
During synchronization a new object was found through a relationship that was not marked cascade PERSIST: EntityB [name=color, value=blue].
I wanted to try to manually insert/update but I couldn't do that. It wants me to have the EntityA specified with PERSIST because it has associations to the entityB
I tried inserting in the reverse and now I'm having issues inserting from entityB.save() when there already exists some entityA and I'm adding a new entityA to entityB

How to set auto increment value to the primary key in ActiveAndroid

I'm new to active Android and I have done CRUD operation, but I am unable to set auto increment for the primary key. I already tried below code but it is of not use to me:
#Table(name = "Employee", id = "EmpId")
public class Employee extends Model {
#Column(name = "empid")
public long empid;
#Column(name="name")
public String name;
}
Here employee is my tablename. I have primary 2 fields, one is empid and name. I need to set auto increment value to the primary key.
How can I do that?
To do an update with a unique column as your pseudo primary key, the annotation would look something like this:
#Column(name = "empid", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
public long empid;
As we can read in a documentation:
One important thing to note is that ActiveAndroid creates an id field
for your tables. This field is an auto-incrementing primary key.
Moreover, if you would like to create custom primary key in you model, you can check solution mentioned in GitHub issue connected with ActiveAndroid, which looks like this:
#Table(name = "Employee", id = "EmpId")
public class Employee extends Model {
#Column(name = "id")
public long id;
#Column(name="name")
public String name;
}
Then, id field is custom primary key, which will be auto-incremented.

GORM Domain Mapping Issue

I've got a bit of a complicated domain model I'm trying to implement and I'm having some trouble. (On top of that, I'm quite new to all this!)
I have a User domain which has multiple roles and multiple tests. The Role domain works great. The Test domain is a bit more compilciated though because it requires two foreign keys instead of just 1 like in the Role domain. The first foreign key is the user_id and the second is a uni_id (university ID).
The User domain model contains the following
class User {
static hasMany = [roles:Role, tests:Test]
Integer userId
...
static mapping = {
table 'user_data'
id generator: 'assigned', name: 'userId', type: 'long'
userId column: 'user_id'
version false
roles joinTable:[name:'user_role', key:'user_id']
tests joinTable:[name:'user_test', key:'user_id'] // Here is where I run into trouble
}
static constraints = {
}
}
The Test domain contains
class Test {
static belongsTo = User
static hasMany = [users:User]
static hasOne = [uni:Uni]
Integer testId // primary key
String testType
static mapping = {
table 'test'
id generator: 'assigned', name: 'testId', type: 'long'
testId column: 'test_id'
users joinTable:[name:'user_test', key:'test_id']
uni joinTable:[name:'user_test', key:'test_id'] // If I leave this out, everything is groovy
version false
}
static constraints = {
}
}
and the Uni domain contains
class Uni {
static belongsTo = Test
static hasMany = [tests:Test]
Integer uniId // primary key
String shortName
String fullName
static mapping = {
table 'uni'
id generator: 'assigned', name: 'uniId', type: 'long'
uniId column: 'uni_id'
version false
tests joinTable:[name:'user_test', key:'uni_id']
}
static constraints = {
}
}
If its not clear, what I'm trying to do is pull in the University ID, Test ID, and User ID to a table user_test to find based on the User ID which tests they have taken. Is there a simple way to do this?
The kinds of errors I'm getting lead me to believe that for some reason it is trying to perform all actions on the table test instead of user_test. For example,
Unsuccessful: alter table test add uni_id int not null
I'd like to be able to access the test and university information corresonding to the specific user via user.tests.testType and user.tests.uni.fullName or something to that extent. What am I doing wrong? More importantly, is there a better way to do this?! Thanks in advance!
Edit 1: something interesting I just thought of.. a user can have multiple tests, but the inverse isn’t true. A given test will never be shared among multiple people. So I think that changes things a bit.. I'll do some reading and post if I come up with anything new.
Edit 2: Here's the Role domain
class Role {
static belongsTo = User
static hasMany = [users:User]
Integer roleId
String shortName
String roleName
Integer roleLevel
static mapping = {
table 'role'
id generator: 'assigned', name: 'roleId', type: 'long'
roleId column: 'role_id'
users joinTable:[name:'user_role', column:'user_id', key:'role_id']
version false
}
static constraints = {
}
}
Edit 3: I am now trying to store all test information in the Test domain model and simply choose the Uni name to store as a field in Test, but am getting weird errors when I try this. My new files look like this
class User {
static hasMany = [roles:Role, tests:Test]
Integer userId
static mapping = {
table 'user_data'
id generator: 'assigned', name: 'userId', type: 'long'
userId column: 'user_id'
version false
roles joinTable:[name:'user_role', key:'user_id']
}
static constraints = {
}
}
and
class Test {
static belongsTo = User
Integer testId // primary key
Integer testTypeId
String testTypeName
String testUni
Date testDate
static mapping = {
table 'test'
id generator: 'assigned', name: 'testId', type: 'long'
testId column: 'test_id'
version false
}
static constraints = {
}
}
but now I'm getting the following error when I try to run it Caused by: org.hibernate.MappingException: Missing type or column for column[tests_test] on domain[User] referencing[Test]
Any idea what that's about?
Ok, one issue you have is that you're trying to share the User-to-Test association join table with the Test-to-Unit association. That's not going to work.
Lets look at it in database terms. I'm not an ASCII art expert, so I hope this diagram doesn't make your eyes bleed.
user_data (userId) |---|< (user_id) user_test (test_id) >|---| (testId) test
The diagram above shows the database implementation of the many-to-many association between the User and Test domain classes. You can see that the user_data.userId links to user_test.user_id and user_test.test_id links to test.testId.
Now here's where it starts to get weird. There are two different associations between Test and Uni: a bidirectional one-to-one and a one-to-many. I just don't understand that. But I want to illustrate an important issue with your join tables, so here it is.
test (testId) |---|< (test_id) user_test (uni_id) >|---| (uniId) uni
Because you're using the same join table (user_test) for two different associations you're asking GORM to create a table like this:
USER_TEST
- USER_ID
- TEST_ID
- UNIT_ID
GORM won't do that because join tables are supposed to have only two fields. Not only that, but also you're defining a many-to-many in database terms, and yet a bidirectional one-to-one and a one-to-many in GORM terms. Ouch!
TODO
The first change I recommend is to use a different join table for the Test-Uni association.
Finally got everything working (after a bit of modification in terms of the domain model)
class User {
static hasMany = [roles:Role, tests:Test]
Integer userId
static mapping = {
table 'user_data'
id generator: 'assigned', name: 'userId', type: 'long'
userId column: 'user_id'
version false
roles joinTable:[name:'user_role', column:'role_id', key:'user_id']
}
static constraints = {
}
}
and
class Test {
User user
Integer testId // primary key
String testType
String testUni
Date testDate
static mapping = {
table 'test'
id generator: 'assigned', name: 'testId', type: 'long'
testId column: 'test_id'
version false
}
static constraints = {
}
}
with
class Uni {
Integer uniId // primary key
String shortName
String fullName
static mapping = {
table 'uni'
id generator: 'assigned', name: 'uniId', type: 'long'
uniId column: 'uni_id'
version false
}
static constraints = {
}
}
So now what I'm doing is selecting the university from a drop down tab in my GSP and just saving it in Test as the string testUni. Then, the big change was removing all joinTables between the three and adding User user to Test. I'm still a little fuzzy on why what I was doing before didn't work, but I won't complain about a working app!