Add auto_increment in JPA entity - java

I use this entity definition for JPA:
#Entity
#Table(name = "payment_transactions")
public class PaymentTransactions implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", unique = true, updatable = false, nullable = false)
private int id;
#Column
private Date date;
#Column
private Integer year;
.....
}
Table is successfully created:
CREATE TABLE `payment_transactions` (
`id` int(11) NOT NULL,
....
PRIMARY KEY (`id`),
}
Table is successfully created.
But I would like MariaDB to auto-generate unique table key value. Like this:
CREATE TABLE `payment_transactions` (
`id` int(11) NOT NULL auto_increment,
....
PRIMARY KEY (`id`),
}
What is the proper way to configure this with JPA?

Related

Saving Record in Relation Spring Boot

I am creating a project in spring boot which creates record by api call.
so I have two table ( name and phone ) below is my domain:
#Entity
#Table(name = "name")
public class Name {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
#Column(name = "name", nullable = false)
private String name;
#Column(name = "active", nullable = false)
private boolean active = true;
#LazyCollection(LazyCollectionOption.FALSE)
#OneToMany(mappedBy = "name")
#JsonIgnoreProperties("name")
private List<Phone> phones;
}
And
#Entity
#Table(name = "phone")
public class Phone {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
#Column(name = "number", nullable = false)
private String number;
#Column(name = "active", nullable = false)
private boolean active = true;
#ManyToOne(targetEntity= Name.class)
#JoinColumn(name="name_id"))
private Name name;
}
The Code to create the name is as follows:
public Name createNewName(Name createName) {
Name newName = new Name();
newName = NameRepo.save(createName);
return newName;
}
And Repository is:
#Repository
public interface NameRepository extends PagingAndSortingRepository<Name, Long> {}
So My problem is when i send a request using api to call this, Name does not store Phone values and also does not link if exist.
My request is as follows:
{
"name": "testrretf",
"active": true,
"phones":[{
"id":1
}]
}
This request should link the new Name to existing Phone id=1
And
{
"name": "testrretf",
"active": true,
"phones":[{
"number":"Test Phone",
"active":true,
}]
}
This request should create a Phone and link to the created Name.
Please help me..
Thanks,
UPDATE# Below is the Create Table Query:
CREATE TABLE `name` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`active` bit(1) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `IDX_NAME` (`name `),
KEY `IDX_NAME_ACTIVE` (`active`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
CREATE TABLE `phone` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`active` bit(1) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`name_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_PHONE_ACTIVE` (`active`),
KEY `fk_name_phone` (`name_id`),
CONSTRAINT `fk_name_phone` FOREIGN KEY (`name_id`) REFERENCES `name` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1

HIbernate Foreign key must have same number of columns as the referenced primary key Error

I have these two tables in my database:
CREATE TABLE classroom_trainee (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
trainee_id BIGINT(20) NOT NULL,
classroom_id BIGINT(20) NOT NULL,
completed BOOLEAN,
notes VARCHAR(255),
result INT(3),
feedback BOOLEAN DEFAULT 0,
PRIMARY KEY (id),
FOREIGN KEY (trainee_id)
REFERENCES user (id),
FOREIGN KEY (classroom_id)
REFERENCES classroom (id)
);
CREATE TABLE trainee_presence (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
classroom_trainee_id BIGINT(20) NOT NULL,
day INT(2) NOT NULL,
presence BOOLEAN,
notes VARCHAR(255),
PRIMARY KEY (id),
FOREIGN KEY (classroom_trainee_id)
REFERENCES classroom_trainee (id)
);
and this is the Entities that I have:
UserEntity.java:
....
public class UserEntity implements Serializable {
...
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "manager_id")
private UserEntity manager;
#Column(name = "email", nullable = false, unique = true)
private String email;
#Column(name = "forename")
private String forename;
#Column(name = "surname")
private String surname;
...
ClassroomTraineeEntity.java
....
public class ClassroomTraineeEntity {
.....
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne
#JoinColumn(name="trainee_id")
private UserEntity trainee;
#ManyToOne
#JoinColumn(name="classroom_id")
private ClassroomEntity classroom;
....
TraineePresenceEntity.java
....
public class TraineePresenceEntity {
.......
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne
#JoinColumn(name="classroom_trainee_id")
private ClassroomTraineeEntity classroomTrainee;
#Column(name = "day")
private Integer day;
#Column(name = "presence")
private Boolean presence;
...
When in TraineePresenceEntity I use
#Column(name="classroom_trainee_id")
private Integer classroomTraineeId;
It all works fine and dandy, but with a ClassroomTraineeEntity object I get this exception:
Caused by: org.hibernate.MappingException: Foreign key (FKn85t08ggb5n6ail459koe0sm8:trainee_presence [classroom_trainee_id])) must have same number of columns as the referenced primary key (classroom_trainee [classroom_id,trainee_id])
Anyone knows how I can solve this problem?

#PrimaryKeyJoinColumn: Joining tables by primary key not working

I have below two tables:
`message` (
`id` varchar(150),
`Message` varchar(1000) ,
PRIMARY KEY (`id`)
)
fallback_status (
message_key varchar(150),
fallback_delivere` tinyint(1),
fallback_read tinyint(1),
fallback_answered tinyint(1),
PRIMARY KEY (message_key)
)
I don't have any foreign key relationship at database level. I have created two entity for these tables
#Entity
#Table(name = "message")
public class Message {
#Id
#Column(name = "id", unique = true)
private String key;
#Column(name = "message")
String message
#OneToOne
#PrimaryKeyJoinColumn(name = "id", referencedColumnName = "message_key")
private MessageFallbackStatus messageFallbackStatus;
}
and
#Entity
#Table(name = "fallback_status")
public class MessageFallbackStatus {
#Id
#Column(name="message_key")
private String messageKey;
#Column(name="fallback_delivered")
private boolean fallbackDelivered;
#Column(name="fallback_read")
private boolean fallbackRead;
#Column(name="fallback_answered")
private boolean fallbackAnswered;
}
With this configuration Hibernate not able to persist data in fallback_status table.
my questions are:
Is the foreign key relationship is mandatory at database level?
what would be the proper mapping for this scenario?
thanks for any help.

Many to many relation in spring framework

Currently I'm working on a Spring Framwork application to try out how it works.
I'm having trouble with a many to many relationship and inserting data into it.
As example I'm making something to store orders containing one or multiple items through a link table.
I would like to store one order at a time, including all products related to it (products are already existing). The problem is that when I try to store data, the orderId isn't stored in the product_order table and gives me the following error:
""Column 'ORDER_ID' cannot be null"".
Has anyone a clue about what i'm doing wrong? Or if it's just not possible this way.
SQL structure & Java code is at the end.
The way I try to store the data is:
curl -i -X POST -H "Content-Type:application/json" -d '{
"code" : "Test",
"statusId" : 2,
"userId" : 1,
"productOrders" : [ {
"price" : 1.0,
"amount" : 2,
"product" : {
"productId" : 1
}
}, {
"price" : 2.0,
"amount" : 3,
"product" : {
"productId" : 2
}
} ]
}' http://localhost:8080/order
This is the SQL structure i'm using:
CREATE TABLE `user` (
`USER_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`USER_NAME` VARCHAR(20) NOT NULL,
`USER_BALANCE` DOUBLE UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`USER_ID`)
);
CREATE TABLE `product` (
`PRODUCT_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`PRODUCT_NAME` VARCHAR(20) NOT NULL,
`PRODUCT_PRICE` DOUBLE UNSIGNED NOT NULL,
`PRODUCT_DESCRIPTION` VARCHAR(45),
PRIMARY KEY (`PRODUCT_ID`)
);
CREATE TABLE `order` (
`ORDER_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`ORDER_USER_ID` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`ORDER_ID`),
CONSTRAINT `FK_ORDER_USER_ID` FOREIGN KEY (`ORDER_USER_ID`)
REFERENCES `user` (`USER_ID`)
);
CREATE TABLE `product_order` (
`ORDER_ID` INT(10) UNSIGNED NOT NULL,
`PRODUCT_ID` INT(10) UNSIGNED NOT NULL,
`AMOUNT` INT(10) UNSIGNED NOT NULL,
`PRICE` DOUBLE NOT NULL,
PRIMARY KEY (`ORDER_ID`,`PRODUCT_ID`),
CONSTRAINT `FK_PRODUCT_ORDER_ORDER_ID` FOREIGN KEY (`ORDER_ID`)
REFERENCES `order` (`ORDER_ID`),
CONSTRAINT `FK_PRODUCT_ORDER_PRODUCT_ID` FOREIGN KEY (`PRODUCT_ID`)
REFERENCES `product` (`PRODUCT_ID`)
);
And this are my classes (removed the getters/setters, left the annotations)
#Entity
#Table(name = "product")
public class Product implements java.io.Serializable {
private Integer productId;
private String name;
private String description;
private Double price;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "PRODUCT_ID", unique = true, nullable = false)
#Column(name = "PRODUCT_NAME", nullable = false)
#Column(name = "PRODUCT_PRICE", nullable = false)
#Column(name = "PRODUCT_DESCRIPTION", nullable = false)
}
#Entity
#Table(name = "`order`")
public class Order implements java.io.Serializable {
private Integer orderId;
private Integer userId;
private Set<ProductOrder> productOrders = new HashSet<>(0);
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ORDER_ID", unique = true, nullable = false)
#Column(name = "ORDER_USER_ID")
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.order", cascade = CascadeType.ALL)
}
#Entity
#Table(name = "product_order")
#AssociationOverrides({
#AssociationOverride(name = "pk.order",
joinColumns = #JoinColumn(name = "ORDER_ID")),
#AssociationOverride(name = "pk.product",
joinColumns = #JoinColumn(name = "PRODUCT_ID")) })
public class ProductOrder implements java.io.Serializable {
private ProductOrderId pk = new ProductOrderId();
private Double price;
private Integer amount;
#EmbeddedId
//Getter/setter for primaryKey (pk)
#Transient
//Link to product
#Column(name = "PRICE")
#Column(name = "AMOUNT")
}
#Embeddable
public class ProductOrderId implements java.io.Serializable {
private Product product;
private Order order;
#ManyToOne
//link to Product
#ManyToOne
//Link to Order
}

foreign key constraint fails - hibernate

I have problem when i try add data to table USERS. First my DB and classes.
DB structure:
CREATE TABLE IF NOT EXISTS `admins` (
`ADMIN_ID` int(10) unsigned NOT NULL AUTO_INCREMENT ,
`USERNAME` varchar(45) NOT NULL,
`PASSWORD` varchar(45) NOT NULL,
`AUTHORITY` varchar(45) NOT NULL,
PRIMARY KEY (`ADMIN_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `lecturers` (
`LECTURER_ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`NAME` varchar(45) NOT NULL,
`SURNAME` varchar(45) NOT NULL,
`TITLES` varchar(45) NOT NULL,
`USERNAME` varchar(45) NOT NULL,
`PASSWORD` varchar(45) NOT NULL,
`AUTHORITY` varchar(45) NOT NULL,
`LEC_DESCRIPTION` varchar(100) NOT NULL,
PRIMARY KEY (`LECTURER_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=40;
CREATE TABLE IF NOT EXISTS `roles_name` (
`role_id` int(1) NOT NULL,
`authority` varchar(45) NOT NULL,
UNIQUE KEY `role_id` (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `roles_name` (`role_id`, `authority`) VALUES
(1, 'ROLE_ADMIN'),
(2, 'ROLE_USER'),
(3, 'ROLE_LECTURER');
CREATE TABLE IF NOT EXISTS `users` (
`USER_ID` int(10) unsigned NOT NULL AUTO_INCREMENT ,
`NAME` varchar(45) NOT NULL,
`SURNAME` varchar(45) NOT NULL,
`username` varchar(45) NOT NULL,
`PASSWORD` varchar(45) NOT NULL,
`USER_DESCRIPTION` varchar(100) NOT NULL,
`AUTHORITY` varchar(45) NOT NULL,
`ENABLED` tinyint(1) NOT NULL,
PRIMARY KEY (`USER_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=50000;
CREATE TABLE IF NOT EXISTS `roles_map` (
`rm_id` int(10) unsigned NOT NULL,
`user_id` int(10) unsigned,
`admin_id` int(10) unsigned,
`lecturer_id` int(10) unsigned,
`username` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`role_id` int(1) NOT NULL,
PRIMARY KEY (`rm_id`),
FOREIGN KEY (`user_id`) REFERENCES `users` (`user_id`),
FOREIGN KEY (`lecturer_id`) REFERENCES `lecturers` (`lecturer_id`),
FOREIGN KEY (`admin_id`) REFERENCES `admins` (`admin_id`),
FOREIGN KEY (`role_id`) REFERENCES `roles_name` (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
RolesMap.java
#Entity
#Table(name = "roles_map")
public class RolesMap {
#Id
#Column(name = "RM_ID", unique = true, nullable = false)
private int rm_id;
//#Column(name = "USER_ID", unique = true)
//private int user_id;
#Column(name = "ADMIN_ID", unique = true)
private int admin_id;
#Column(name = "LECTURER_ID", unique = true)
private int lecturer_id;
#Column(name = "USERNAME", unique = true, nullable = false)
private String username;
#Column(name = "PASSWORD", unique = true, nullable = false)
private String password;
#Column(name = "ROLE_ID", unique = true, nullable = false)
private int role_id;
#ManyToOne(cascade={CascadeType.ALL})
#JoinColumn(name = "user_id")
private User user;
//getters and setters
}
User.java
#Entity
#Table(name = "users")
public class User {
#Id
#Column(name = "USER_ID", unique = true, nullable = false)
private int user_id;
#Column(name = "NAME", nullable = false)
private String name;
#Column(name = "SURNAME", unique = true, nullable = false)
private String surname;
#Column(name = "USERNAME", unique = true, nullable = false)
private String username; // zamiast username
#Column(name = "PASSWORD", unique = true, nullable = false)
private String password;
#Column(name = "USER_DESCRIPTION", nullable = false)
private String userDescription;
#Column(name = "AUTHORITY", nullable = false)
private String authority = "ROLE_USER";
#Column(name = "ENABLED", nullable = false)
private int enabled;
#OneToMany(mappedBy="user", cascade=CascadeType.ALL)
private List <RolesMap> rolesMap;
//getters and setters
}
adding method
public String addUser() {
Session sess = null;
try {
sess = UserDao.getSessionFactory().openSession();
sess.beginTransaction();
RolesMap roles = new RolesMap();
//roles.setrUser(user);
User user = new User();
roles.setPassword(getPassword());
roles.setRole_id(2);
roles.setUsername(getUsername());
user.setName(getName());
user.setSurname(getSurname());
user.setUsername(getUsername());
user.setPassword(getPassword());
user.setUserDescription(getUserDescription());
user.setAuthority(getAuthority());
user.setEnabled(getEnabled());
user.setRolesMap(new ArrayList<RolesMap>());
user.getRolesMap().add(roles);
sess.save(user);
sess.getTransaction().commit();
//getUserService().addUser(user);
return SUCCESS;
} catch (DataAccessException e) {
e.printStackTrace();
}
return ERROR;
}
When I try use this method I have error:
Cannot add or update a child row: a foreign key constraint fails (soeOne2.roles_map, CONSTRAINT roles_map_ibfk_2 FOREIGN KEY (lecturer_id) REFERENCES lecturers (LECTURER_ID))
But I do not know why, because I'm trying to add data to the USER and ROLESMAP tables. I think when you add data to a table ROLESMAP/USER field lecturer_id and admin_id in ROLESMAP table shuld be NULL. Can anyone tell me what I'm doing wrong?
It is because lecturer_id=0 is NOT lecturer_id=null.
Your application try to save lecturer_id=0 and the database think that 0 is the ID of an item in table lecturers.
So the first workarround is to replace the int with Integer, so that you can assign lecturer_id = null
#Column(name = "LECTURER_ID", unique = true)
private Integer lecturer_id;
And I think you need this modification for all other references that work the same way.
The second point is, that the way you map references between entities is not the jpa (hibernate) way. I strongly recommend that you read something about mapping relations (OneToOne, OneToMany, ManyToOne, ManyToMany) For example the Hibernate Reference Chapter 7. Collection mapping and 8. Association Mappings

Categories