Make hibernate continue the sequence from a previous database for id generation values - spring

I have this entity:
#Entity
#Table(name = "street_type")
public class StreetType {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "type")
private String type;
#OneToMany(mappedBy = "streetType")
private Set<TransitRoute> transitRoutes;
Which i want to has the id auto-incremented, the problem is that in the database i have already some data, so the last row it has an id of 5, so how i make Hibernate to start the auto-increment value to start with 5 and continue with the given strategy.
I found the GenericGenerator decorator but i do not found a good example of how to use it. I already see this post but i got the same error of ERROR: relation "hibernate_sequence" does not exist

Related

JPA repository findBy foreign key for ManyToMany relationship

I have the following relationship in the data base
Database Diagram
And these are the entities
Apartment.java
#Entity
#Table(name = "apartment")
#Data
public class Apartment {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_apartment")
private long id;
#ManyToMany
#JoinTable(
name = "apartment_facility",
joinColumns = #JoinColumn(name = "id_apartment"),
inverseJoinColumns = #JoinColumn(name = "id_facility"))
#Column(name = "city")
private String city;
#Column(name = "country")
private String country;
}
Facility.java
public class Facility {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_facility")
private long id;
#Column(name = "name")
private String name;
}
My question is how can I create a findBy method in JpaRepository in order to find all Apartments having the required facilities
I'm thinking of the result of this request:
api/apartments/findByFacilities?facilities=gym,pool,parking
I have tried to do a query but couldn't quite get it. Also tried using Jpa as following
List<Apartment> findByFacilities(#RequestParam("facilities") List<String> facilities);
But I'm getting the following error. Is there a walkaround?
Failed to convert from type [java.lang.String] to type [java.lang.Long]
In your first code block List <Facility> facilities = new ArrayList<>(); I guess you forgot to add the code line.
When I look at your link below, I understand that you want to search by the name of the facility.
api/apartments/findByFacilities?facilities=gym,pool,parking
For this, your code in Repository should be as follows:
List<Apartment> findDistinctByFacilitiesNameIn(List<String> facilities);
If we don't add distinct supported keyword here, each record repeats as many as the facilities it contains.
If you want to search differently like, not like, etc., See the supported keywords inside method names table here: Query Creation document.

Spring Boot JPA - OneToMany relationship and database structure

I wonder what database structure would be the best option in my case:
I have entity Questionnaire:
#Table(name = "questionnaire")
public class Questionnaire extends BaseEntity {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#OneToMany(mappedBy = "fieldStatus")
private List<QuestionnaireField > fieldStatusList;
}
#Table(name = "questionnaire_field")
public class QuestionnaireField extends BaseEntity {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "questionnaire_id")
private Long questionnaireId;
#Column(name = "field_id")
private Long fieldId; //this is id related to the other table Field
#Column(name = "completed")
private boolean completed; //because I need some additional informations like completed I think I can't use ManyToMany between Questionnaire and Field
#ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.REMOVE})
#JoinColumn(name = "questionnaire_id")
private Questionnaire questionnaire;
As you see each Questionnaire can have multiple QuestionnaireFields, BUT each QuestionnaireField is of type Field (hence I added private Long fieldId). Table Field can have 10.000 different fields.
Summary:
one questionnaire can have e.g. 10 Fields, the second one 20 another Fields etc. To store fields related to some particular Questionnaire I created QuestionnaireField table with 2 columns: private Long questionnaireId; and private Long fieldId; . The question is if it is a good approach? That are plain columns not related to any Foreign Key... I try to find the best solution to save Questionnaire with related QuestionnaireFields that are a subset of a big Field table...

When does #GenerateValue in hibernate execute

I am using an #Entity with a CrudRepository to create an entry in my MySQL database, and I was wondering at what point the #GeneratedValue(strategy = GenerationType.AUTO) execute and generate the auto increment value?
#Entity
#Table(name = "all_contacts")
public class Contact {
//Ideally this would be set as foreign key to application's user schema
private long userId;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column( name="contactid")
private long contactId;
#NotNull
private String name;
//getters and setters
}
//
public interface ContactRepository extends CrudRepository<Contact, Long> { }
I ask because I want to access the value of the contactId through its getter, but do I have to wait until the ContactRepository.save() is called?
We can't know the new assigned id of that entity prior to executing the SQL INSERT statement.
So, yes you need to ContactRepository.save() or any command that trigger SQL INSERT statement before can get that id. But save is better because it is guaranteed that it will always return ID.
We get the generated value once SQL insert statement is executed. We can't know the value is being assinged before save(). GenerationType.AUTO number generator generates automatic object IDs for entity objects and this generated numeric value is used for primary key field.
#Entity
public class Entity {
#Id #GeneratedValue(strategy=GenerationType.AUTO) int id;
}

SequenceGenerator not using next value of databasesequence

I have a problem in my application. I have an Oracle database with a sequence on a table. When i view the sequence in the database it says that last_number is 33800. However, when I try inserting a new object from my application the generated id is not 33800, but rather a smaller number. My guess is that Hibernate or whatever just finds the next available number. It does happen that my application deletes rows in the table, thus causing holes in the id-sequence. So, eventually I will get an exception because an ID i am trying to insert has already been used.
How can I configure the application so that it is always the sequence's last number + 1 that is used? I thought that this was default behavior, as I cannot recall encountering this problem.
This is my entity:
#Entity
#SequenceGenerator(name = "SequenceIdGenerator", sequenceName = "MY_SEQ", allocationSize = 20)
#Table(name = "myEntity")
public class myEntity {
private Long id;
#Id
#Column(name = "id")
#GeneratedValue(generator = "SequenceIdGenerator")
public Long getId() {
return id;
}
public void setId(final Long id) {
this.id = id;
}
}
you can let hibernate handle this by
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id", nullable = false)
private Long id;
you can read more about it here https://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing
You are using ORACLE so for you GenerationType.SEQUENCE will work as GenerationType.IDENTITY is not supported by Oracle

EntityNotFoundException in Hibernate Many To One mapping however data exist

I'm getting an error
Caused by: javax.persistence.EntityNotFoundException: Unable to find tn.entities.AgenceBnq with id 01
when I get AgenceBnq through Employee
Employee class:
#Table(name = "EMPLOYEE")
#NamedQuery(name = "Employee.findById", query = "SELECT e FROM Employee e WHERE e.employeMat = ?1"),
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "EMPLOYEE_MAT", unique = true, nullable = false, length = 15)
private String employeeMat;
...
#ManyToOne
#JoinColumn(name = "AGENCE_COD")
private AgenceBnq agenceBnq;
}
#Entity
#Table(name="AGENCEBNQ")
public class AgenceBnq implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="AGENCE_COD", unique=true, nullable=false, length=10)
private String agenceCod;
...
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="agenceBnq")
private Set<Employee> employees;
}
I'm calling namedQuery Employee.findById in DAO to retrieve data and I have to get AgenceBnq from Employee but get this error while calling query.getResultList()
#NotFound( action = NotFoundAction.IGNORE) isn't useful for me because data exist in AGENCEBNQ table and I have to retrieve date through Employee.
Is this a bug in hibernate ? I'm using hibernate version 3.6.7.Final
Firstly, You dont need query for it, the EnityManger.find(Employee.class, YOUR_ID) will do the job.
Secondly dont use ? in your queries but names (e.employeMat = :id) as it is easier to debug and less error prones for complicated queries.
Finally, check your DB table if the AGENCE_COD column in Employee table really contains the valid ID for your entitity that crashes (and that it length matches the ID length of AgenceBnq). It should work, the typical reason why it doesnt will be that your Employe.AGENCE_COD has defualt value and when creatubg the new EMploye you add it only to the Agence but you did not set Agence in the Employ.

Resources