I have some problem with insert in hibernate.
Suppose I have 2 entity
#Entity
public class User{
#Id
#GeneratedValue
int user_id;
String name;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "utente_id")
list<City> cities;
}
#Entity
public class City{
int user_id
int city_id
}
if I try a create class User and add a list of city but when I try to save, receive this error:
Caused by: java.sql.SQLException: Foreign key constraint violation occurred
this because user_id in class City must be equal at user_id in User, but hibernate first inserts and then updates.
How do i revolve this?
Try first to persist the User object to DB.
Only after you persist you can get the generated value of user_id.
Then you can create the City object, set the user_id field, and persist it.
Related
This error occurs when my Postmapping method tries to save a quiz.
Here's the controller.
`
#PostMapping("/quizzes")
public Quiz postQuiz(#Valid #RequestBody Quiz quiz) {
return quizRepo.save(quiz);
}
Now here is the User entity whose association is the Quiz entity (it has 5 fields).
public class User {
//other fields/columns
#OneToMany(targetEntity = Quiz.class, cascade = CascadeType.ALL)
#JoinColumn(name = "user_id", referencedColumnName = "id")
private List<Quiz> quizzes;
}
Theuser_id` field is the foreign key in the quiz table and not a declared field in the Quiz class/entity.
I was thinking just declaring the relationship will populate the foreign key column, in this case user_id, will just be the primary key of the owning entity but it seems at the the time of saving in the PostMapping method, the user_id is null. I've tried anything I possibly can but to no avail.
I get this error when requesting service line:
List<Order> orders = ordersRepository.getByCustomerId(id);
Error:
org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [5] did not match expected type [nz.webshop.models.Customer.Customers (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [5] did not match expected type [nz.webshop.models.Customer.Customers (n/a)]
Repository:
public interface OrdersRepository extends JpaRepository<Order, Integer> {
List <Order> getByCustomerId(Integer customerId);
}
Entities:
#EntityA:
#Table(name = "orders")
public class Order {
#ManyToOne(targetEntity=Customers.class)
#JoinColumn (name = "customer_id", referencedColumnName="customer_id")
private Integer customerId;
...getters/setters
#EntityB:
#Table (name ="customer")
public class Customers {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "customer_id")
private Integer customerId;
#OneToMany(targetEntity = Order.class, mappedBy = "customerId")
private List<Order> Order;
...getters/setters
Where tables are like this:
CREATE TABLE orders
(
order_id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customer (customer_id)
);
CREATE TABLE customer
(
customer_id INT AUTO_INCREMENT PRIMARY KEY,
first_name VARCHAR(50) ,
last_name VARCHAR(50)
);
Update:
I changed EntityA as follows:
#EntityA:
#Table(name = "orders")
public class Order {
#Column(name = "customer_id")
private Integer customerId;
#ManyToOne(targetEntity=Customers.class)
private Customer customer;
...getters/setters
But then when requesting the same service line new error: org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet. Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'order0_.customer_customer_id' in 'field list'.
Where is the problem could be?
It looks like the Order.customerId property is not set up correctly. You're requesting that ManyToOne find Customer models based on their IDs, but then you're loading the models as Integers. Try this instead:
#ManyToOne
#JoinColumn(name = "customer_id", referencedColumnName="customer_id")
private Customer customer;
Let me know if this works, and if not, we can troubleshoot some more.
When I am trying to delete User from the users table with the help of Hibernate using its id it occurs an exception:
Caused by:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`ewp`.`user_task_history`, CONSTRAINT `FK_mkjvq9fr0e1hdgi3ekl0hluuu` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))`.
And Code:
Class User:
#Entity
#Table(name = "users")
public class User implements UserDetails{
...
#OneToMany(targetEntity = UserTaskHistory.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user")
private Set<UserTaskHistory> userTaskHistories;
...
Class UserTaskHistory:
#Entity
#Table(name = "user_task_history")
public class UserTaskHistory{
...
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "user_id")
private User user;
...
The same thing happens when I'm trying to delete other objects having foreign keys. Is there any other way to make Hibernate to delete by itself all the objects that have links of foreign keys of the object I'm trying to delete?
I have a RECIPE table that has OneToMany relationship with the INGREDIENT table because a single recipe can have many ingredients. The issue is that if a user deletes an ingredient (which sets all fields (ingredient_id and ingredient) to NULL by frontend), then the row containing relationship of both the tables RECIPE_INGREDIENT is deleted but the row in the Ingredient table still exists. Can't we tell Hibernate to delete that rows also?
Oracle table
create table recipe(id number primary key,
name varchar2(25) unique);
create table ingredient(ingredient_id number(4) primary key,
ingredient varchar2(40));
create table recipe_ingredient(recipe_id number(4),
ingredient_id number(4),
constraint recipe_fk foreign key(recipe_id)
references recipe(recipe_id),
constraint ingredient_fk foreign
key(ingredient_id) references
ingredient(ingredient_id));
Ingredient and Recipe POJO
#Entity
#Table(name = "ingredient", uniqueConstraints={
#UniqueConstraint(columnNames="INGREDIENT_ID")
})
public class Ingredient implements Serializable {
#Id
#Column(name = "INGREDIENT_ID", unique=true, nullable=false)
#SequenceGenerator(name="seq_ingredient", sequenceName="seq_ingredient")
#GeneratedValue(strategy=GenerationType.AUTO, generator="seq_ingredient")
private Integer ingredientId;
#Column(name = "INGREDIENT")
private String ingredient;
/*#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="RECIPE_ID")
private Recipe recipe;*/
//getter and setters
#Entity
#Table(name = "recipe")
public class Recipe implements Serializable {
#Id
#Column(name = "id")
private Integer id;
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
#JoinTable(name = "recipe_ingredient", joinColumns = { #JoinColumn(name = "recipe_id") }, inverseJoinColumns = { #JoinColumn(name = "ingredient_id") })
private List<Ingredient> ingredients;
//getters and setter
}
DAO Code
public class RecipeDaoImpl implements RecipeDao {
public void addRecipe(Recipe recipe) {
getSession().saveOrUpdate(recipe);
}
}
Log that shows that the row in INGREDIENT table still exists whereas Hibernate is just deleting row from 'RECIPE_INGREDIENT' table.
Please see following that ingredient_id with null is deleted. In both cases, it is updating ingredient.recipe_id as NULL.
Received following from frontend:
RecipeController - Recipe[recipeId=126,name=Sandwich,ingredients=[Ingredient[ingredientId=270,ingredient=Salt],[ingredientId=<null>,quantity=<null>]]]
Hibernate: update RECIPE set NAME=? where RECIPE_ID=?
Hibernate: update ingredient set INGREDIENT=? where INGREDIENT_ID=?
Hibernate: delete from recipe_ingredient where recipe_id=?
Hibernate: insert into recipe_ingredient (recipe_id, ingredient_id) values (?, ?)
So the database table has,
INDREDIENT
INGREDIENT_ID INGREDIENT
271 Salt
272 Sugar
RECIPE_INDGREDIENT
RECIPE_ID INDREDIENT_ID
126 271
Have you implemented the equals() and hashcode() methods correctly in the Receipe and Indgredient classes? If not then that could be the cause why the rows in indgredient table are not deleted. Read this article for more details.
I'm creating an application where one large aspect is the ability for users to share content with friends. I'm trying to represent this in the object model and I'm having trouble getting the association to work properly. I'm using a mapping table that records the friender and the friendee, both of which are represented by the primary key (id) of the user. A user can have many friends, and also be referenced by other users. This is what the schema looks like:
Users:
int user_id (PK)
varchar(32) email
varchar(64) password
Users_Map:
int users_map_id (PK)
int friendee_id (FK references users(user_id))
int friender_id (FK references users(user_id))
And this is how I have the User entity set up:
#Data
#Entity
#Table(name = "users")
public class User extends AbstractPersistable<Long> {
#Id
#Column(name = "user_id")
private Long id;
#Column
private String email;
#Column
private String password;
#OneToMany
#JoinTable(name = "users_map",
joinColumns = { #JoinColumn(name = "friender_id") },
inverseJoinColumns = { #JoinColumn(name = "friendee_id") })
private List<User> friends;
}
I run into the following error when deploying the application:
org.hibernate.AnnotationException: A Foreign key refering
com.x.webapp.data.entity.User from
com.x.webapp.data.entity.User has the wrong number of
column. should be 2
I've tried quite a few other configurations, including adding a "referencedColumnName" attribute to each #JoinColumn, but they have also yielded errors. I'm also not entirely sure whether the schema I currently have is the best way to go about mapping users together.
I appreciate any help!
Removing the extension of AbstractPersistable fixed the problem - that contained an #Id reference and clashed with the #Id reference I put inside of User.