Hibernate insert ID into auto-increment column - mysql

I am using Sprint Boot, Sprint Data JPA, Hibernate 4 and MySQL. I have a table with an autoincrement column. I can insert new entities ok and the column auto-increments. Sometimes though I want to specify the ID when doing an insert but Hibernate appears to ignore any ID value I set.
Table definition:
#Entity
#Table(name = "example")
public class Example implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
... more columns ....
}
How can I have both auto-increment when no id is set AND allow setting of the ID by my application?

Its because your ID is not that will be stored in the database,rather than that it is considering #GeneratedValue(strategy = GenerationType.IDENTITY) which is generating values for you

Related

Unable to reset SQL id to 1

I am unable to reset the id of the objects that I am adding to SQL, through JPA. I tried to write a native query to truncate when I use my deleteAll method, which works, no errors, but the autogenerated id is still not 1.
I tried "ALTER TABLE task AUTO_INCREMENT = 1" after deleting, same result.
My method used for resetting
#Transactional
#Modifying
#Query(value = "ALTER TABLE task AUTO_INCREMENT = 1", nativeQuery = true)
void resetId();
My entity id
public class Task {
#Id
#Column(name = "id", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

how can I create a Single Entity from two other tables/Entity JPA hibernate making a INNER JOIN result with a common key

How can I create a Single Entity from two other tables/Entity in JPA/hibernate making a INNER JOIN result with a common key. I was using the below code but it gives me a full join instead of an inner join. it give me records from the meal table even if the
"id 1" does not exist in the allergies table, example:
{id=1, name='tacos', description='Mexican food', price ='10',peanuts=null, celery=null, sesameSeeds=null}
How can constrain to don't return any records if the 'id' is missing from the secondary table allergies? to show only records when the primary key is present in both tables.
I want something like this instead:
{id=1, name='tacos', description='Mexican food', price ='10',peanuts='no', celery='no', sesameSeeds='no'}
Please advise.
#Entity
#Table(name = "meal")
#SecondaryTable(name = "allergens", pkJoinColumns = #PrimaryKeyJoinColumn(name = "meal_id"))
class Meal {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
Long id;
#Column(name = "name")
String name;
#Column(name = "description")
String description;
#Column(name = "price")
BigDecimal price;
#Column(name = "peanuts", table = "allergens")
boolean peanuts;
#Column(name = "celery", table = "allergens")
boolean celery;
#Column(name = "sesame_seeds", table = "allergens")
boolean sesameSeeds;
// standard getters and setters
}

Cannot delete parent and child

I have two entities using Spring and Hibernate
Entity A:
#Entity
#Table(name = "A")
public class A {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "a")
private B b;
Here i have a one to one relationship with Entity B, the owner of the relationship is Entity A.
Entity B:
#Entity
public class B{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#OneToOne
#JoinColumn(name = "a_ID")
private A a;
Saving the entities gives no problem. Entity B gets the ID of entity A in the Database.
But when i delete Entity A, I also want to delete Entity B that belongs to A.
When I delete i get the error:
MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails
I think my declarations in my entities are correct. What is the problem here?
Edit
When I inspect the table of Entity B and specifically the Foreign key to Entity A it says Restricted on Update en on Delete
set orphanRemoval property to true in class A
like this: #OneToOne(mappedBy = "a", cascade = CascadeType.ALL, orphanRemoval = true)

Alternative for #Formula?

I have two objects:
#Table(name = "user")
User
#Id
Integer id
Integer uuid;
and reservation:
#Table(name = "reservation")
Reservation
#Id
Integer id;
Integer uuid;
My goal is:
#Table(name = "reservation")
Reservation
#Id
Integer id;
Integer uuid;
#Formula("(SELECT * FROM user b WHERE b.uuid = uuid )")
List<User> users;
The problem is #Formula doesnt work with objects.
How to include list of all users in reservation with same uuid?
I found this but maybe there is better option
https://stackoverflow.com/a/37502703/3871754
Support of relationships that references non-PK columns is an optional feature. In simple cases it's supported by Hibernate
#NotAudited
#OneToMany
#JoinColumn(name = "uuid", referencedColumnName = "uuid")
private List<Barrier> barriers = new ArrayList<>();
and implemented Serializable for Reservation

Many to Many child removel JPA

Hi i have many to many relationship and entities are here:
#Entity
public class Company implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer idcompany;
//bi-directional many-to-many association to Client
#ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinTable(name="company_client",
joinColumns=#JoinColumn(name="company_idcompany",
referencedColumnName="idcompany"),
inverseJoinColumns=#JoinColumn(name="client_idclient",
referencedColumnName="idclient"))
Set<Client> clients = new HashSet<Client>();
and second entity
#Entity
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int idclient;
#ManyToMany(mappedBy="clients",cascade = CascadeType.PERSIST , fetch =
FetchType.LAZY )
Set<Company> companies = new HashSet<Company>();
and here is details of date in all 3 tables
---------------------------------------------
company table client table company_client table
id name id name fk_compny fk_client
1 Oracle 1 Abc 1 1
2 XYZ 1 2
when i want to remove row from client table e.g "XYZ" id=2
Client cl = em.find(Client.class,2);
em.remove(cl);
it throws exception "Cannot delete or update a parent row: a foreign key constraint fails " .
How to remove this row