I'm Trying to create table "User" in DB with using spring data JPA. How can I do that? [duplicate] - spring

This question already has answers here:
Create user table name with hibernate
(2 answers)
Closed 22 days ago.
why can't I create table in db - "user" using spring data JPA ?
#Entity
#Data
#NoArgsConstructor(access = AccessLevel.PRIVATE, force = true)
#RequiredArgsConstructor
#Table(name = "user")
public class User implements UserDetails {
private static final long serialVersionUID = 1;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private final String username;
private final String password;
private final String fullName;
private final String street;
private final String city;
private final String state;
private final String zip;
private final String phoneNumber;
}
I get an error while initializing the program
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table user (id bigint not null, city varchar(255)...
I change Class name from "user" to "users" and the problem was solved but what is the reason of that error ?

user is a reserved word in SQL and Postgres. Many databases have reserved words, so you can run into collision sometimes.
Actually, JPA supports the following syntax for specifiyng the tablename (you can escape the table name)
#Table(name="\"user\"")
but it may cause problems in the future (in a query for example) and you should avoid using reserved words
So it is better to use users word instead

Related

How to update column in JPA native query which annothed with #Lob

I have an entity class and repository. Here I'm trying to execute update query but not working.
How to update Lob column in native query or any another solution on jpa query to update Lob column.
#Entity
#Table(name = "comment")
public class Comment implements Serializable {
#Basic
#Lob
#Column(name="Article_COMMENT", columnDefinition="TEXT")
private String articleComment;
#Basic
#Column(name = "ID_ARTICLE")
private Long articleId;
}
#Repository
public interface commentRepository extends JpaRepository<Comment, Long> {
#Query(value = "UPDATE comment set articleComment=: articleComment WHERE articleId =: articleId", nativeQuery=true)
void updateComment(#Param("articleComment") String articleComment, #Param("articleId") Long articleId );
}
Error:
No results were returned by query.
JpaSystemException thrown with message: could not extract ResultSet; nested exception is org.hibernate.exception.GenericJDBCException: could not extract ResultSet
Your question is very vague so I can answer on assumptions only. I think You want to update the articalComment field of your Entity. You can simply use .save() method of JpaRepository. Your code should be as follows. Here I am also assuming that your articleId is unique identifier to your entity class.
#Entity
#Table(name = "comment")
public class Comment implements Serializable {
#Basic
#Lob
#Column(name="Article_COMMENT", columnDefinition="TEXT")
private String articleComment;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID_ARTICLE")
private Long articleId;
}
Now your Id should be unique and has a #Id Annotation to identify it inside spring data JPA.
You don't have to add any code inside of your JPA repository. Simply call commentRepository.save(commentObject) method. If commentObject has an ID as 0 then a new Comment will be created. If the ID is a positive value and is present in your table that particular row will be updated not created.
remove the space try this way
UPDATE comment set articleComment=:articleComment WHERE articleId =:articleId

join table and get data based on field value JPA

I have two entities
#Entity
public class Module {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String descr;
#OneToMany(cascade = {CascadeType.ALL})
#JoinColumn(name="ID", referencedColumnName="ID")
private List<Permissions> perms;
}
#Entity
public class Permissions {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private Integer clientId;
private String role;
private Character endorseCreate;
private Character endorseUpdate;
private Character endorseDelete;
private Character endorseView;
I am trying to fetch data by first Module.name and Permissions.clientId and Permissions.role
Something like in sql
select * from Module m, Permissions p where m.id=p.id and p.clientId=1 and p.role='ADMIN'
How can I achieve using JPA, I am using spring data aswell.
Can a method be declared in CRUD Repo provided by spring data?
I think the issue is I am unable to find way to pass values to fetch data.
Any help is greatly appreciated

Self-Referencing record leading to "Direct self-reference leading to cycle" exception

I have self referencing class
#Entity
#Table(name = "contacts")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Document(indexName = "contacts")
public class Contacts implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "username")
private String username;
#Column(name = "password_smartlpc")
private String password;
#Column(name = "full_name")
private String fullName;
#ManyToOne
private Contacts companyContact;
}
But for my one database record
id full_name username password company_contact_id
5 JAK movies abc xyz 5
This record has company_contact_id as its self id.Which while retrieving goes into self-referencing cycle.
Enter: com.fps.web.rest.errors.ExceptionTranslator.processRuntimeException()
with argument[s] =
[org.springframework.http.converter.HttpMessageNotWritableException: Could not
write content: Direct self-reference leading to cycle (through reference
chain: java.util.UnmodifiableRandomAccessList[2]-
>com.fps.domain.Contacts["companyContact"]-
>com.fps.domain.Contacts["companyContact"]); nested exception is
com.fasterxml.jackson.databind.JsonMappingException: Direct self-reference
leading to cycle (through reference chain:
java.util.UnmodifiableRandomAccessList[2]-
>com.fps.domain.Contacts["companyContact"]-
>com.fps.domain.Contacts["companyContact"])]
Work Around i have tried
(fetch = FetchType.LAZY) = gives same error as above.
#JsonIgnore : removes error but does not retrieves Company_Contact_id
#JsonManagedReference #JsonBackReference same as above.
Unfortunately i cannot change database or alter it.Since its legacy.Any more things i can try ??
Thanks
Try using DTOs in JHipster, you'll get more control over JSON serialization rather than simply exposing your entity especially when you are constrained by legacy database schema.

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;
}

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