so I followed this tutorial video (source)
to create a Java Enterprise Web Application and have ran into a problem. As this is pretty much the first time working with stuff like this for me I am clueless regarding how to solve this.
When trying to run the project I get an error saying "The module has not been deployed. See the server log for details." After some time trying to find out what was wrong I figured it is most likely the error I have in my "Student.java"-class. It says "cannot find symbol classTable. Create Subclass Create Test Class". What may be the problem here? I'm not sure what code would be relevant as I am a complete beginner to this, but all my files are exact copies of the source code-wise. Here is Student.java:
package com.joseph.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* #author Joseph
*/
#Entity
#Table
#NamedQueries({#NamedQuery(name="Student.getAll",query="SELECT e FROM Student e")})
public class Student implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column
private int studentId;
#Column
private String firstname;
#Column
private String lastname;
#Column
private int yearLevel;
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getYearLevel() {
return yearLevel;
}
public void setYearLevel(int yearLevel) {
this.yearLevel = yearLevel;
}
public Student(int studentId, String firstname, String lastname, int yearLevel) {
this.studentId = studentId;
this.firstname = firstname;
this.lastname = lastname;
this.yearLevel = yearLevel;
}
public Student(){}
}
Related
I'm working with many-to-one relationship between my two tables(Employee and Department) in which any Employee can work in more than one department. I used the #ManyToOne annotation on the Department object field which I created in Employee entity class. Now when I persist the Employee entity with a particular department, it works fine but when I try to persist another Employee entity with the same department, it creates a new Department entity with the same name and persists it with different id. What I expect it to do is that when I persist an Employee entity with already persisted department, it should just update the foriegn key of the Employee entity to point the id of that department. Sorry if I didnt got the many-to-one concept totally.
EMPLOYEE entity
package com.test.domain;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.TableGenerator;
#Entity
public class Employee {
#TableGenerator(name="Empl_Gen", table="ID_GEN",pkColumnName="GEN_NAME",valueColumnName="GEN_VALUE", initialValue=0, allocationSize=1)
#Id#GeneratedValue(generator="Empl_Gen",strategy=GenerationType.TABLE)
private Long id;
private String Name;
private String Country;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="DEPT_ID")
private Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
}
DEPARTMENT entity
package com.test.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.TableGenerator;
#Entity
public class Department {
#TableGenerator(name="DEP_GEN",table="ID_GEN",pkColumnName="GEN_NAME",valueColumnName="GEN_VALUE", pkColumnValue="DEP_GEN",initialValue=0,allocationSize=1)
#Id#GeneratedValue(strategy=GenerationType.TABLE,generator="DEP_GEN")
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.test.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.test.domain.Employee;
import com.test.service.EmployeeService;
/**
* Handles requests for the application home page.
*/
#Controller
#RequestMapping("/addEmployee")
public class HomeController {
#Autowired
EmployeeService service;
#RequestMapping(method=RequestMethod.GET)
public String getform(Model model)
{
model.addAttribute("employee",new Employee());
return "home";
}
#RequestMapping(method=RequestMethod.POST)
public String setform(Employee employee)
{
service.save(employee);
return"success";
}
}
package com.test.dao;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.test.domain.Employee;
#Repository
#Transactional
public class Employeedaoimpl implements Employeedao
{
#PersistenceContext
EntityManager manager;
#Override
public void save(Employee employee) {
manager.persist(employee);
}
}
Try this:
#TableGenerator(name="DEP_GEN",table="ID_GEN",pkColumnName="GEN_NAME",valueColumnName="GEN_VALUE", pkColumnValue="DEP_GEN",initialValue=0,allocationSize=1)
#Id#GeneratedValue(strategy=GenerationType.TABLE,generator="DEP_GEN")
#Column(name = "DEPT_ID")
private Long id;
i am using a strategy=GenerationType.TABLE on my Employee table and i defined a generator using #TableGenerator(name="Empl_Gen", table="ID_GEN",pkColumnName="GEN_NAME",valueColumnName="GEN_VALUE") and specified the generator in #GeneratedValue(generator="Emp_Gen") using the name of the generator which is "Empl_Gen". when the application starts up , it creates a table named "ID_GEN" but the table dont contain any Generator of the name ""Empl_Gen".Infact it will create a generator "EMPLOYEE" which is same as my entity class name. Also the value of the ""GEN_VALUE" doesnt get incremented when persisting the employee entity.The ids for the employee are generated randomly too..
package com.test.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.TableGenerator;
#Entity
public class Employee {
#TableGenerator(name="Empl_Gen", table="ID_GEN",pkColumnName="GEN_NAME",valueColumnName="GEN_VALUE")
#Id#GeneratedValue(generator="Empl_Gen",strategy=GenerationType.TABLE)
private Long id;
private String Name;
private String Country;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
}
I don't know how I can persist an entity(with enum) to the database.
When I fill my form like this;
form.setTypZamowienia(SlownikZamowienie.SENIOR)
then 666 is stored in the database. But when I try like this;
form.setTypZamowienia(SlownikZamowienie.valueOf(request.getParameter("typKlienta").trim()));
0 is stored in the database.
How do I make this work?
For any help I will be very grateful.
My enum :
public enum SlownikZamowienie
{
JUNIOR(42),
SENIOR(666),
PRINCIPAL(31416);
private final int wartosc;
SlownikZamowienie(int wartosc) {
this.wartosc = wartosc;
}
}
My Entity:
package test.jpa.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import test.enums.SlownikZamowienie;
#Entity
#Table(name="Piess")
public class Pies implements Serializable {
private static final Long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
int id;
#Column(name = "imie")
String imie;
#Enumerated
#Column(name = "rasa")
SlownikZamowienie typzamowienia;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public SlownikZamowienie getTypzamowienia() {
return typzamowienia;
}
public void setTypzamowienia(SlownikZamowienie typzamowienia) {
this.typzamowienia = typzamowienia;
}
}
As of JPA 2.1 you can use an attribute converter (known as a UserType in the Hibernate world). See these two articles for details on how to implement such a solution:
www.thoughts-on-java.org/jpa-21-type-converter-better-way-to/
www.thoughts-on-java.org/jpa-21-how-to-implement-type-converter/
I'm using Toplink Grid(Eclipselink) as the my JPA implementation framework.
I met a a exception as below while I tried to use Criteria to query a Embeddable object:
Exception [EclipseLink-6119] (Eclipse Persistence Services - 2.1.2.v20101206-r8635): org.eclipse.persistence.exceptions.QueryException
Exception Description: The join expression
Query Key conInfo
Base domain.de1003.Employee is not valid, or for a mapping type that does not support joining.
Query: ReportQuery(referenceClass=Employee )
at org.eclipse.persistence.exceptions.QueryException.mappingForExpressionDoesNotSupportJoining(QueryException.java:659)
at org.eclipse.persistence.internal.queries.JoinedAttributeManager.prepareJoinExpression(JoinedAttributeManager.java:851)
at org.eclipse.persistence.internal.queries.JoinedAttributeManager.prepareJoinExpressions(JoinedAttributeManager.java:778)
at org.eclipse.persistence.internal.queries.ReportItem.initialize(ReportItem.java:171)
at org.eclipse.persistence.queries.ReportQuery.prepare(ReportQuery.java:1035)
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:509)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.checkPrepare(ObjectLevelReadQuery.java:822)
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:470)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:710)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1038)
at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:381)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1124)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2917)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1291)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1273)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1247)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:479)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getResultList(EJBQueryImpl.java:714)
And the code I tried are as below:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<ContactInfo> cq = cb.createQuery(ContactInfo.class);
Root<Employee> root = cq.from(Employee.class);
cq.select(root.<ContactInfo> get("conInfo"));
cq.where(cb.le(root.<Long> get("employId"), 3));
TypedQuery<ContactInfo> q = em.createQuery(cq);
List<ContactInfo> results = q.getResultList();
In Which ContactInfo is an embeddable class consisting of an address and set of phones. Phone is String filed.
Any help will be very appreciated.
I check the question related to this issue:
JPA - Criteria API and EmbeddedId
But it didn't solve my question.
And I can't find any example code.
TO James:
The entity code as below:
package domain.de1003;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.AttributeOverrides;
import javax.persistence.AttributeOverride;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;
import oracle.eclipselink.coherence.integrated.config.GridCacheCustomizer;
import org.eclipse.persistence.annotations.Customizer;
import com.tangosol.io.pof.PofReader;
import com.tangosol.io.pof.PofWriter;
import com.tangosol.io.pof.PortableObject;
#Entity(name="Employee")
#Table(name="EMPLOYEE")
#Customizer(oracle.eclipselink.coherence.integrated.config.GridCacheCustomizer.class)
public class Employee implements PortableObject,Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "EM_ID")
private long employId;
#Column(name = "FIRSTNAME")
private String firstName;
#Column(name = "LASTNAME")
private String lastName;
#Embedded
#AttributeOverrides({
#AttributeOverride(name="homePhone", column=#Column(name="HOMEPHONE")),
#AttributeOverride(name="workPhone", column=#Column(name="WORKPHONE"))
})
private ContactInfo conInfo;
#Version
private long version;
public long getEmployId() {
return employId;
}
public void setEmployId(long employId) {
this.employId = employId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public ContactInfo getConInfo() {
return conInfo;
}
public void setConInfo(ContactInfo conInfo) {
this.conInfo = conInfo;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
#Override
public void readExternal(PofReader pofReader) throws IOException {
employId = pofReader.readLong(1);
firstName = pofReader.readString(2);
lastName = pofReader.readString(3);
version = pofReader.readLong(4);
}
#Override
public void writeExternal(PofWriter pofWriter) throws IOException {
pofWriter.writeLong(1, employId);
if(firstName != null) pofWriter.writeString(2, firstName);
if(lastName != null) pofWriter.writeString(3,lastName);
pofWriter.writeLong(4, version);
}
#Override
public String toString() {
return "["
+ "employId = " + employId
+ " firstName = " + firstName
+ " lastName = " + lastName
+ " contact inforamtion: " + conInfo
+ "]";
}
}
and Entity ContactInfo
package domain.de1003;
import java.io.IOException;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import oracle.eclipselink.coherence.integrated.config.GridCacheCustomizer;
import org.eclipse.persistence.annotations.Customizer;
import com.tangosol.io.pof.PofReader;
import com.tangosol.io.pof.PofWriter;
import com.tangosol.io.pof.PortableObject;
#Embeddable
#Customizer(oracle.eclipselink.coherence.integrated.config.GridCacheCustomizer.class)
public class ContactInfo implements PortableObject,Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "ADDRESS")
private String address;
#Column(name = "HOMEPHONE")
private String homePhone;
#Column(name = "WORKPHONE")
private String workPhone;
#Column(name = "CELLPHONE")
private String cellPhone;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getHomePhone() {
return homePhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public String getWorkPhone() {
return workPhone;
}
public void setWorkPhone(String workPhone) {
this.workPhone = workPhone;
}
public String getCellPhone() {
return cellPhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
#Override
public void readExternal(PofReader pofReader) throws IOException {
address = pofReader.readString(1);
homePhone = pofReader.readString(2);
workPhone = pofReader.readString(3);
cellPhone = pofReader.readString(4);
}
#Override
public void writeExternal(PofWriter pofWriter) throws IOException {
if(address != null) pofWriter.writeString(1, address);
if(homePhone != null) pofWriter.writeString(2, homePhone);
if(workPhone != null) pofWriter.writeString(3, workPhone);
if(cellPhone != null) pofWriter.writeString(4, cellPhone);
}
#Override
public String toString() {
return "["
+ "address = " + address
+ " homePhone = " + homePhone
+ " workPhone = " + workPhone
+ " cellPhone = " + cellPhone
+ "]";
}
}
For the equivalent JQPL
Query query = em.createQuery("SELECT e.conInfo FROM Employee e where e.employId < 3");
worked.
I tried reproducing this in the latest EclipseLink (a 2.5 nightly) but couldn't. I suspect it might be fixed with criteria API changes to add On support - can you give it a shot to confirm it? You might have to turn off the cache to use the latest version of EclipseLink to test with though.
Check if conInfo is the correct name of your attribute (include your entity code).
Does the equivalent JPQL work?
I am trying to get rid of this error:
Exception Description: [class utilisateurs.modeles.Utilisateur] uses a non-entity [class java.util.Collection] as target entity in the relationship attribute [field adresses].
at org.eclipse.persistence.exceptions.ValidationException.nonEntityTargetInRelationship(ValidationException.java:1343)
.........
org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processORMetadata(PersistenceUnitProcessor.java:526)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1320)
... 36 more
with the following entity:
utilisateurs.modeles;
import adresses.Adresse;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
#Entity(name="Utilisateur")
public class Utilisateur implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
public void setAdresses(Collection<Adresse> adresses) {
this.adresses = adresses;
}
private String firstname;
private String lastname;
private String login;
#ManyToOne(cascade=CascadeType.PERSIST)
private Collection<Adresse> adresses;
public Collection<Adresse> getAdresses() {
return adresses;
}
public Utilisateur() {
}
public Utilisateur(final String firstname, final String lastname, final String login) {
this.firstname = firstname;
this.lastname = lastname;
this.login = login;
}
//getters and setters here
#Override
public int hashCode() {
int hash = 0;
hash += (int) id;
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Utilisateur)) {
return false;
}
Utilisateur other = (Utilisateur) object;
if (this.id != other.id) {
return false;
}
return true;
}
}
If you have any idea please.
Adresse is not an Entity, maybe you just forgot the #Entity annotation on that class?
The #ManyToOne annotation defines a relationship between entities.