Hibernate Select certain columns that are entity objects - java

I am trying to use Spring Boot (and obviously I am a newbie) along with Hibernate.
#Entity
public class UserRole {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long userRoleId;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="user_id")
private User user;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name="role_id")
private Role role;
}
I am trying to retrieve only the List of User Objects without having to rely on a UserRole object List to take them.
I tried the following into my UserRoleRepository
#Query("select u.user from user_role u where u.role = :role")
public ArrayList<User> findByRoleQ(Role role);
When i tried the above query I got a missmatch mapping error When i tried to run it as follows
2018-01-27 18:14:12.299 WARN 10720 --- [ main]
ationConfigEmbeddedWebApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'afdempUisuxAdminApplication':
Unsatisfied dependency expressed through field 'userRoleService';
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'userRoleServiceImpl': Unsatisfied
dependency expressed through field 'userRoleRepository'; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'userRoleRepository': Invocation of init
method failed; nested exception is java.lang.IllegalArgumentException:
Validation failed for query for method public abstract
java.util.ArrayList
org.afdemp.uisux.repository.UserRoleRepository.findByRoleQ(org.afdemp.uisux.domain.security.Role)!
What am I doing wrong and is there a way to make it return only the User column (thus User List)?

Related

How to make a correct ManyToMany relation with Hibernate and Kotlin? (Getting BeanCreationException)

I have the following code which throws the following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory; nested exception is org.hibernate.MappingException: Could not determine type for: java.util.Set, at table: project, for columns: [org.hibernate.mapping.Column(type)]
I think I am creating the #ManyToMany mapping in a wrong way. Here are the main classes in question:
#Entity
class Project (
#GeneratedValue
#Id
var id : UUID? = null,
var owner: Int,
#get:ManyToMany(mappedBy = "project", fetch = FetchType.EAGER)
var type: MutableSet<Type> = mutableSetOf()
)
The second class is:
class Type(
#GeneratedValue
#Id
var id: UUID? = null,
var oldId: Int,
var value: String,
#get:ManyToMany(fetch = FetchType.EAGER)
#get:JoinColumn(name = "project_id")
var projects: MutableSet<Project> = mutableSetOf()
)
A Project can have many Types and a Type can belong to many projects. What is causing the exception?
In Project entity,
#get:ManyToMany(mappedBy = "project", fetch = FetchType.EAGER)
var type: MutableSet<Type> = mutableSetOf()
Here, mappedBy has value project,
while, in Type entity, variable name is projects,
So, if you just update Project entity's type field as follow:
#get:ManyToMany(mappedBy = "projects", fetch = FetchType.EAGER)
var type: MutableSet<Type> = mutableSetOf()
This should work just fine. Hope that helps.
Change
#get:ManyToMany
#get:JoinColumn
to
#ManyToMany
#JoinColumn

JpaRepository Retrieving Child from Parent

How to Retrieving Child from Parent ?.
Let say i have parent class and child class. And i want to retrieve list of child from parent side.
This is my Parent Class.
+import ...
#Entity
public class Parent {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
#OneToMany(mappedBy="parent", cascade = CascadeType.REMOVE, orphanRemoval = true)
private List<Child> Childs = new ArrayList<>();
private String name;
* Getter and Setter are hide
}
This is my Parent Child.
+import ...
#Entity
public class Child {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
#ManyToOne()
private Parent parent;
private String childNote;
* Getter and Setter are hide
}
This is my Repository
#Repository
public interface ParentRepository extends JpaRepository<Parent, Long> {
#Query(value = "SELECT p.childs FROM Parent p where p.id =:id")
List<Child> findxx(Long id);
}
That give me an error :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-03-05 00:59:16.281 ERROR 444 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testApplication': Unsatisfied dependency expressed through field 'parentRepo'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'parentRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.example.test.ParentRepository.findxx(java.lang.Long)!
... I cut-off this line's
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'parentRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.example.test.ParentRepository.findxx(java.lang.Long)!
... I cut-off this line's
Caused by: java.lang.IllegalArgumentException: Validation failed for query for method public abstract java.util.List com.example.test.ParentRepository.findxx(java.lang.Long)!
... I cut-off this line's
Caused by: java.lang.IllegalArgumentException: org.hibernate.QueryException: could not resolve property: childs of: com.example.test.Parent [SELECT p.childs FROM com.example.test.Parent p where p.id =:id]
... I cut-off this line's
Caused by: org.hibernate.QueryException: could not resolve property: childs of: com.example.test.Parent [SELECT p.childs FROM com.example.test.Parent p where p.id =:id]
... I cut-off this line's
Caused by: org.hibernate.QueryException: could not resolve property: childs of: com.example.test.Parent
at org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:73) ~[hibernate-core-
... I cut-off this line's
Really need your advice.
Jigu
SELECT c FROM Child c where c.parent.id =:id

Spring-Data-Elastic Search and Spring-Data-Cassandra Having Issues with MapId

I am trying to have Spring-Data-Cassandra and Spring-Data-Elasticsearch work together. Below is the problem which I am facing.
org.springframework.beans.BeanInstantiationException: Failed to instantiate
[org.springframework.format.support.FormattingConversionService]: Factory method
'mvcConversionService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'personRepository': Invocation of init method failed;
nested exception is java.lang.IllegalArgumentException: Unsuppored ID type interface
org.springframework.data.cassandra.repository.MapId
My Repositories interfaces are in different packages and I have marked the with
#EnableElasticsearchRepositories(basePackages = "com.mycompany.mp.search.repo")
and
#EnableCassandraRepositories(basePackages = { "com.infy.mycompany.repository" })
I have used MappingCassandraConverter and org.springframework.data.elasticsearch.core.DefaultEntityMapper. The elasticsearch template is init like this new ElasticsearchTemplate(client, new DefaultEntityMapper());
My Person object looks like this.
import org.springframework.data.cassandra.mapping.Table;
/**
* Created by allahbaksh_asadullah on 01/11/16.
*/
#Table(value = "person")
#Document(indexName = "person")
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Long id;
private String firstName;
private String lastName;
//Getters and Setters
}
If I don't mark my Person.java with the #Document annotation things works fine but ElasticSearch will not work then.
What is the best way make it work?

Hibernate autogeneration of Id doesn't seem to be working

I have my entity called Post which has Id as a primary key.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "Id", unique = true, nullable = false)
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
In above code you may see GenerationType.IDENTITY which I would assume is responsible for generating a new ID in case of creation of a new Post.
However, when I make a HTTP POST with this JSON:
{"id":0,"title":"test","viewCount":0,"body":"test","tags":"","answerCount":0,"commentCount":0,"postTypeId":1,"favoriteCount":0,"creationDate":"Nov 25, 2015 11:43:22 AM","acceptedAnswerId":0,"lastEditorUserId":0,"score":0}
I am getting this error:
SEVERE: Servlet.service() for servlet [rest] in context with path [/StackExchange] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not execute statement; nested exception is org.hibernate.exception.GenericJDBCException: could not execute statement] with root cause
java.sql.SQLException: Field 'Id' doesn't have a default value
I haven't set AI though, maybe that is the cause. But I am unable to alter the table. The data in the table are from SQL dumps and I can't alter it to set Id as AutoIncrement

hibernate #JoinColumnsOrFormulas annotation with #id

I have entity with 2 id and one has annotation #JoinColumnsOrFormulas
#AccessType("property")
#Id
#NotFound(action=NotFoundAction.IGNORE)
#ManyToOne(optional = false, fetch = FetchType.LAZY)
#JoinColumnsOrFormulas({
#JoinColumnOrFormula( column=#JoinColumn(name="RE", referencedColumnName="ret")),
#JoinColumnOrFormula( formula=#JoinFormula(value="ret2", referencedColumnName="rete"))
})
#Fetch(FetchMode.SELECT)
private rete ret;
but it throws exception:
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource... Invocation of init method failed; nested exception is java.lang.ClassCastException: org.hibernate.mapping.Formula cannot be cast to org.hibernate.mapping.Column
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:502)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:84)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:282)
Unable to #id annotation with #JoinColumnsOrFormulas???

Categories