ERROR: Unknown column '0_.' in 'where clause' - java

Hi I'm trying to make output of annual salary using below function:
List results=session.createQuery("select comp.annual_sales from employee").list();
My tables are defined as below
#Entity(name="company")
#Table(name="company")
public class company{
#Id
#Column(name="company_id")
private int company_id;
#Column(name="company_name")
private String company_name;
#Column(name="annual_sales")
private double annual_sales;
#Column(name="founding_date")
#Temporal(TemporalType.DATE)
private Date founding_date;
/*#OneToMany(mappedBy = "comp", cascade = CascadeType.ALL, orphanRemoval = true)
private List<employee> emps; //= new HashSet<employee>();*/
public company(){}
public company(int company_id, String company_name, double annual_sales, Date founding_date){
this.company_id=company_id;
this.company_name=company_name;
this.annual_sales=annual_sales;
this.founding_date=founding_date;
}
}
#Entity(name="employee")
#Table(name="employee")
public class employee{
#Id
#Column(name="employee_id")
private int employee_id;
#Column(name="first_name")
private String first_name;
#Column(name = "last_name")
private String last_name;
#Column(name="salary")
private int salary;
#Column(name="company")
private int company;
#ManyToOne
#JoinColumn(name="comp")
private company comp;
/*#OneToMany(mappedBy = "emp", cascade = CascadeType.ALL, orphanRemoval = true)
private List<account> accs; //= new HashSet<account>();*/
public employee(){}
public employee(int employee_id, String first_name, String last_name, int salary, int company){
this.employee_id=employee_id;
this.first_name=first_name;
this.last_name=last_name;
this.salary=salary;
this.company=company;
}
}
#Entity(name="account")
#Table(name="account")
public class account{
#Id
#Column(name="account_id")
private int account_id;
#Column(name="bank_name")
private String bank_name;
#Column(name="opening_date")
#Temporal(TemporalType.DATE)
private Date opening_date;
#Column(name="owner")
private int owner;
#ManyToOne
#JoinColumn(name="emp")
private employee emp;
public account(){}
public account(int account_id, String bank_name, Date opening_date, int owner){
this.account_id=account_id;
this.bank_name=bank_name;
this.opening_date=opening_date;
this.owner=owner;
}
}
and the following error comes out:
org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1054, SQLState: 42S22
org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Unknown column 'employee0_.comp' in 'where clause'
I have three major question here:
I have no column or attribute named 'employee0_' and why is it appearing in the error?
I have no 'where clause' sql function but why is such error appearing?
I've looked through many questions but it seemed nobody has similar problem with me nor they could solve my problem. The closest thing I could find was this: ERROR: Unknown column 'user0_.id' in 'field list'
but adding #OnetoMany clause did not solve my problem.
How should I fix this error?

employee0_ is just an alias, that's used by Hibernate in the query. The error itself refers to the column comp, which Hibernate cannot find in the employee table. The where clause is added, because Hibernate needs to load the company entity, which is referred to in the employee entity.
So to fix the error, you should make sure that you actually have a column named comp in the employee table, and if not, either use the correct name in the annotation or create the column.

Related

Eclipselink tries to inset null value in table

I'm currently trying to create a many to many mapping using eclipselink. Please note that for this specific example no table to resolve the relation is used (I kwon that this is not a good practice but it is necassary for this specific example).
I've created a database schema and the tables employee3 and insurance to map. The employee table holds a column called insurance_id which is part of the primary key in order to create the mapping. Same goes for insurance with employee_id.
Now for the code:
Here is the code for the two classes:
First off Employee:
#Entity
#Table(name="employee3", schema = "many_to_many")
public class EmployeeManyToMany
{
protected EmployeeManyToMany()
{
}
#Id
private int id;
private String firstName;
private String lastName;
#ManyToMany(cascade = CascadeType.PERSIST)
private Collection<InsuranceManyToMany> insurance;
public EmployeeManyToMany(int id, String firstName, String lastName)
{
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
insurance = new ArrayList<InsuranceManyToMany>();
}
.....
And Insurance:
#Entity
#Table(name = "insurance", schema = "many_to_many")
public class InsuranceManyToMany
{
#Id
#Column(name = "id")
private int insuranceId;
private String company;
#ManyToMany(mappedBy = "insurance", cascade = CascadeType.PERSIST)
private Collection<EmployeeManyToMany> employee;
protected InsuranceManyToMany()
{
}
public void addEmployee(EmployeeManyToMany emp)
{
employee.add(emp);
}
public InsuranceManyToMany(String company, int insuranceId)
{
this.insuranceId = insuranceId;
this.company = company;
employee = new ArrayList<EmployeeManyToMany>();
}
....
After I create an Employee object and add a list of insurances to it i try to persist it into the database.
Which results in the following error:
javax.persistence.RollbackException: Exception [EclipseLink-4002]
Eclipse Persistence Services - 2.7.3.v20180807-4be1041):
org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: null value
in column "insurance_id" violates not-null constraint
Detail: Failing row contains (1, hans, test, null).
Error Code: 0
Call: INSERT INTO many_to_many.employee3 (ID, FIRSTNAME, LASTNAME) VALUES
(?, ?, ?)
bind => [3 parameters bound]
Query: InsertObjectQuery(swd_ws18_06_Tag3.EmployeeManyToMany#88d98e)
I have no idea why this occures since the values are never null.
Any help is appreciated!
BR
Simon

JPA: Mapping ManyToMany relationship refers to incorrect column name

This question is related to previous question that I asked yesterday.
I have many-to-many relationship between Employee and SkillSet table, with additional column numberOfYears for each relation
employeeId skillSetId numberOfYears
10 101 2
Since I do not have ID column in EmployeeSkillSet table, I am using #IdClass to define the composite key
#Entity
class Employee {
private #Id Long id;
#OneToMany(mappedBy="employeeId")
private List<EmployeeSkillSet> skillSets;
}
class SkillSet {
private #Id Long id;
}
#IdClass(EmpSkillKey.class)
#Entity
class EmployeeSkillSet {
#Id
#Column("employee_id")
private Long employeeId;
#Id
#Column("skill_id")
private #Id Long skillId;
#ManyToOne
private Employee employee;
private int numberOfYears;
}
class EmpSkillKey{
private int employeeId;
private int skillId;
}
interface EmployeeRepository extends JPARepository{
List<Employee> getEmployeesBySkillSetSkillId(long id);
}
The above JPA repository method works fine and gives me list of Employees as per the skillSet ID. But when I try to iterate over the list and get the EmployeeSkillSet object then it throws error, as it tries to map to incorrect column employee instead of employeeId.
List<Employee> emps = employeeRepository.getEmployeesBySkillSetSkillId(101);
for(Employee e: emps){ // this line throws error
EmployeeSkillSet ess = e.getEmployeeSkillSet();
int n = ess.getNumberOfYears();
}
Query generated is something like this. (I have converted it to Employee use case, cannot share actual query)
select ud.employee_id , ud.employee_id , ud.employee , ud.employee_value , rd.employee_id
from employee_skill_set ud left outer join employee rd
on ud.employee=rd.employee_id
where ud.employee_id=?
Exception
WARN - SqlExceptionHelper - SQL Error: 207, SQLState: ZZZZZ
ERROR - SqlExceptionHelper - Invalid column name 'employee'.
org.hibernate.exception.GenericJDBCException: could not extract ResultSet
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:449)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:202)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:137)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:100)
at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:693)
at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:92)
at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1933)
at org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:559)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:261)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:555)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:143)
at org.hibernate.collection.internal.PersistentBag.iterator(PersistentBag.java:294)
May be I cannot define #Id employeeId and #ManyToOne employee in same class. But then how to resolve this?
Nevermind, I found out the solution. Annotated the #ManyToOne relation with #JoinColumn and with actual column name. Not sure why it asked for making updatable and insertable as false. Have to get my basics clear :)
#IdClass(EmpSkillKey.class)
#Entity
class EmployeeSkillSet {
#Id
#Column("employee_id")
private Long employeeId;
#Id
#Column("skill_id")
private #Id Long skillId;
#JoinColumn(name="employee_id", insertable=false, updatable=false)
#ManyToOne
private Employee employee;
private int numberOfYears;
}

JPA Eclipse fails to update foreign key on merge() call

i've found this problem in a lot of posts but i can't find a solution.
I have one entity:
#Entity
#Table(name="UTENTI")
#NamedQueries({
#NamedQuery(name="Utenti.findAll", query="SELECT u FROM Utenti u"),
#NamedQuery(name="Utenti.findByEmail", query="SELECT u FROM Utenti u WHERE u.userId = :mail")
})
public class Utenti implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="ID_UTENTE", nullable = false)
#GeneratedValue(strategy=GenerationType.AUTO)
private BigDecimal id;
#Column(name="USER_ID",unique=true)
private String userId;
private String cognome;
#Temporal(TemporalType.DATE)
private Date dataDiNascita;
private String nome;
private String password;
private String ruolo;
#OneToMany(mappedBy="user",cascade=CascadeType.ALL)
private List<Form> forms;
#ManyToMany(mappedBy="users",cascade=CascadeType.ALL)
private List<Groups> groups;
#OneToMany(mappedBy="utente",cascade=CascadeType.ALL)
private List<CodicePromozionale> codes;
#OneToMany(mappedBy="owner",cascade=CascadeType.ALL)
private List<PacchettoAcquistato> acquisti;
/*getters and setters*/
and another entity:
#Entity
#Table(name="GROUPS")
public class Groups implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="GROUPID", nullable=false)
private String groupId;
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="USER_GROUP",joinColumns={#JoinColumn(name="GROUPID",referencedColumnName="GROUPID")},inverseJoinColumns={#JoinColumn(name="USERID",referencedColumnName="USER_ID")})
private List<Utenti> users;
if i change userId inside my stateless bean and then call merge like so:
this.user.setUserId(newUserId);
this.em.merge(user);
where this.em is the EntityManager
i get this error:
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507- 3faac2b): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`traveldreamdb`.`user_group`, CONSTRAINT `FK_USER_GROUP_USERID` FOREIGN KEY (`USERID`) REFERENCES `UTENTI` (`USER_ID`))
Error Code: 1451
Call: UPDATE UTENTI SET USER_ID = ? WHERE (ID_UTENTE = ?)
bind => [2 parameters bound]
why this happens if i have specified the cascadeType.ALL?How can i resolve it?
From the exception message, it says you have another table in your database, name is user_group. It has a column user_id. This column is referencing to the user_id column of UTENTI table. So, whenever you are trying to update this value, the other table user_group faces the problem as the reference is updated.

org.hibernate.ObjectNotFoundException issue with using list()

The following query throws the exception:
Query query = session.createQuery("from Associate as a order by a.username asc");
associates = query.list();
org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [ca.mypkg.model.Associate#0]
If I create an entry in the database with id of 0 it works just fine. I don't really get it because I'm just trying to load all the entries in the db not just a specific one.
Similar questions I've found have been concerned with trying to load an object with a given ID I'm doing no such thing.
Associate class:
#Table(name = "user")
#XmlRootElement(name = "associate")
public class Associate implements Serializable {
private String username;
private String password;
private String firstName;
private String lastName;
private String userType;
private int id;
private String email;
private String isActive;
private Department dept;
private String lastUpdated;
private String associate_type;
// ...
#Id
#GeneratedValue
public int getId() {
return id;
}
#OneToOne
#JoinColumn(name = "dept")
public Department getDept() {
return dept;
}
From my experience this type of error message usually means it does not find joined entity by mentioned id, and not the entity requested in the query (Associate, in your case).
My guess is that Associate class contains a join entity which has primitive type primary key.

JPA OneToMany bi-directional

I know that there is many question about it but i can not find a good answered for my problem .
I am using Jboss as 7, Spring and Hibernate (4) as JPA 2.0 provider so i have got simple #OneToMany bi-directional relationship :
I have got super class person like that:
#MappedSuperclass
#Inheritance(strategy=InheritanceType.JOINED)
public abstract class Person {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#NotNull
#Size(min = 1, max = 25)
#Pattern(regexp = "[A-Za-z ]*", message = "must contain only letters and spaces")
private String name;
public Person(String name) {
super();
this.name = name;
}
And class Member:
#Entity
#Table(uniqueConstraints = #UniqueConstraint(columnNames = "email"))
public class Member extends Person implements Serializable
{
/** Default value included to remove warning. Remove or modify at will. **/
private static final long serialVersionUID = 1L;
#NotNull
#NotEmpty
#Email
private String email;
#NotNull
#Size(min = 10, max = 12)
#Digits(fraction = 0, integer = 12)
#Column(name = "phone_number")
private String phoneNumber;
#OneToMany(cascade=CascadeType.ALL , mappedBy="member" , fetch=FetchType.EAGER)
private List<Order> orders;
And also class Order:
#Entity
public class Order {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private float price;
#ManyToOne(optional=false)
private Member member;
private String name;
So i think that it is a good configuration, but i test this application in HSQL in memory and i have got error :
Hibernate: alter table Order drop constraint FK48E972E548C740B
2012-09-20 16:25:37 org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table Order drop constraint FK48E972E548C740B
2012-09-20 16:25:37 org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: Blad skladniowy w wyrazeniu SQL "ALTER TABLE ORDER[*] DROP CONSTRAINT FK48E972E548C740B "; oczekiwano "identifier"
Syntax error in SQL statement "ALTER TABLE ORDER[*] DROP CONSTRAINT FK48E972E548C740B "; expected "identifier"; SQL statement:
alter table Order drop constraint FK48E972E548C740B [42001-165]
And also :
Syntax error in SQL statement "CREATE TABLE ORDER[*] (ID INTEGER GENERATED BY DEFAULT AS IDENTITY, NAME VARCHAR(255), PRICE FLOAT NOT NULL, MEMBER_ID BIGINT NOT NULL, PRIMARY KEY (ID)) "; expected "identifier"; SQL statement:
And my JUnit test failed i dont know what is wrong with this configuration ...
this is my simply junit :
#Test
public void testInsertWithOrder(){
Order order = new Order(20.0f, "first stuff");
Order order2 = new Order(40.0f, "secondary stuff");
List<Order> orders = new ArrayList<Order>();
orders.add(order2);
orders.add(order);
Member member = new Member("Member name", "member23#gmail.com", "2125552141", orders);
memberDao.register(member);
List<Member> members = memberDao.findAllOrderedByName();
Assert.assertNotNull(members);
Assert.assertEquals(1, members.size());
}
Change table name from 'order' to something different, like PersonOrder
In your member in Order Class, there are missing #JoinColumn annotation. Try as below.
#ManyToOne(optional=false)
#JoinColumn(name = "memberId", referencedColumnName = "id")
private Member member;
#CycDemo
I am just figure it out and in my constuctor i now have got :
#OneToMany(cascade=CascadeType.ALL , mappedBy="member" , fetch=FetchType.EAGER)
private List<UOrder> orders = new ArrayList<UOrder>();
public Member(String name, String email, String phoneNumber ,List<UOrder> orders) {
super(name);
this.orders = orders;
this.email = email;
for(UOrder o : orders){
o.setMember(this);
}
this.orders = orders;
}
Ant this is it what i need :)))

Categories

Resources