SQL syntax Error on Java Jersey GET CRUD operation - sql

I'm trying to retrieve the information of the faculty with the students attending it and the subjects corresponding to the student.
Here is the SQL error:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM faculty f
inner join student_faculty sf on sf.student_id=s.user_id'
Here is the picture in line 116 the s.user_id is not on yellow color indicating something not right:
Here is it how I want it to look like:
{
"fid": "1",
"name": "Mathematcis",
"enrolled_students": [
{
"id": "student1",
"username": "user",
"full_name": "userstudent",
"subjects": [
{
"id": 1,
"name": "Programim 1"
},
{
"id": 2,
"name": "Programim 2"
},
{
"id": 3,
"name": "Calculus"
},
{
"id": 4,
"name": "Discrete mathematics"
}
]
}
]
Here is how postman shows it:
Here is my code:
public Faculty getFacultyStudent(int id) throws Exception {
Connection connection = null;
Faculty faculty = new Faculty();
Student student = new Student();
student.setSubjectList(new ArrayList<>());
faculty.setStudentList(new ArrayList<>());
try {
connection = new MysqlDbConnectionService().getConnection();
String select = "SELECT f.fid,\n" +
" f.fname,\n" +
" f.university_id,\n" +
" s.user_id,\n" +
" s.username,\n" +
" s.password,\n" +
" s.fullname,\n" +
" s.email,\n" +
" subj.id,\n" +
" subj.name,\n" +
"FROM faculty f\n" +
" inner join student_faculty sf on sf.student_id=s.user_id\n" +
" INNER JOIN student s ON sf.student_id=s.user_id\n" +
" INNER JOIN faculty_subject fs on f.fid = fs.faculty_id\n" +
" inner join subject subj on fs.subject_id = subj.id\n" +
"WHERE fid = ?;";
PreparedStatement ps = connection.prepareStatement(select);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
if(faculty.getFid()==0) {
faculty.setFid(rs.getInt("fid"));
faculty.setFname(rs.getString("fname"));
}
student.setId(rs.getString("user_id"));
student.setUsername(rs.getString("username"));
student.setPassword(rs.getString("password"));
student.setFullName(rs.getString("fullname"));
student.setEmail(rs.getString("email"));
Subject subject=new Subject();
subject.setId(rs.getInt("id"));
subject.setName(rs.getString("name"));
student.getSubjectList().add(subject);
faculty.getStudentList().add(student);
}
} catch (Exception e) {
System.out.println(e + "Retrieve not successful");
}
return faculty;
}
Faculty Class:
package com.common.db.domain;
import com.google.gson.annotations.SerializedName;
import java.util.Collections;
import java.util.List;
public class Faculty {
#SerializedName("id")
private int fid;
#SerializedName("university_id")
private int university_id;
#SerializedName("name")
private String fname;
#SerializedName("Enrolled Students:")
private List<String> studentList;
public Faculty() {
this.fid = fid;
this.university_id=university_id;
}
public void setFid(int fid)
{
this.fid = fid;
}
public int getFid()
{
return fid;
}
public void setUniversityid(int university_id)
{
this.university_id=university_id;
}
public int getUniversityid()
{
return university_id;
}
public void setFname(String fname)
{
this.fname = fname;
}
public String getFname()
{
return fname;
}
public void setStudentList(List<String> studentList) {
this.studentList = studentList;
}
public List<Object> getStudentList()
{
return Collections.singletonList(studentList);
}
}
Student Class:
package com.common.db.domain;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Student {
#SerializedName("id")
private String id;
#SerializedName("username")
private String username;
#SerializedName("password")
private String password;
#SerializedName("fullname")
private String fullName;
#SerializedName("email")
private String email;
#SerializedName("subjects")
private List<Subject> subjectList;
public Student() {
}
public Student(String id, String username, String password, String fullName, String email) {
super();
this.id = id;
this.username = username;
this.password = password;
this.fullName = fullName;
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Subject> getSubjectList() {
return subjectList;
}
public void setSubjectList(List<Subject> subjectList) {
this.subjectList = subjectList;
}
}
Subject Class:
package com.common.db.domain;
import com.google.gson.annotations.SerializedName;
public class Subject {
#SerializedName("id")
private int id;
#SerializedName("name")
private String name;
public Subject() {
this.id = id;
this.name=name;
}
public void setId(int id)
{
this.id=id;
}
public int getId()
{
return id;
}
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
}
Here is my ER Diagram:

I was reading through the code and the error and it appears to be just your sentence.
"subj.name , \n" + "FROM faculty f\n" +
That comma after the column name and before the FROM clause is causing that error.
Try to remove it and test it again

Related

Not getting expected record from database when comparing dates in spring boot

I am passing date and email through post request and accepting them in validatebasicdetails api.
When I am comparing the recieved date that is in yyyy-MM-dd format to the one which is stored in database, I am unable to fetch the expected record.
Post request:
{
"emailAddress":"smith#abc.com",
"dateOfBirth":"2019-12-12"
}
When I am printing the object I received from post request it's printing it as
Customer [uniqueIdNumber=null, dateOfBirth=Wed Dec 12 05:30:00 IST 1990, emailAddress=smith#abc.com, firstName=null, lastName=null, idType=null, customeraddress=null, simdetails=null]
the date here is not in yyyy-MM-dd format.
Customerdto.java
package com.jpa.Proj.DTOs;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import com.jpa.Proj.Entities.Customeraddress;
import com.jpa.Proj.Entities.Simdetails;
public class CustomerDTO {
String uniqueIdNumber;
#DateTimeFormat(pattern="yyyy-MM-dd")
Date dateOfBirth;
String emailAddress;
String firstName;
String lastName;
String idType;
Customeraddress customeraddress;
Simdetails simdetails;
public String getUniqueIdNumber() {
return uniqueIdNumber;
}
public CustomerDTO(String uniqueIdNumber, Date dateOfBirth, String emailAddress, String firstName, String lastName,
String idType, Customeraddress customeraddress, Simdetails simdetails) {
super();
this.uniqueIdNumber = uniqueIdNumber;
this.dateOfBirth = dateOfBirth;
this.emailAddress = emailAddress;
this.firstName = firstName;
this.lastName = lastName;
this.idType = idType;
this.customeraddress = customeraddress;
this.simdetails = simdetails;
}
#Override
public String toString() {
return "Customer [uniqueIdNumber=" + uniqueIdNumber + ", dateOfBirth=" + dateOfBirth + ", emailAddress="
+ emailAddress + ", firstName=" + firstName + ", lastName=" + lastName + ", idType=" + idType
+ ", customeraddress=" + customeraddress + ", simdetails=" + simdetails + "]";
}
public CustomerDTO() {
super();
}
public void setUniqueIdNumber(String uniqueIdNumber) {
this.uniqueIdNumber = uniqueIdNumber;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
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 String getIdType() {
return idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
public Customeraddress getCustomeraddress() {
return customeraddress;
}
public void setCustomeraddress(Customeraddress customeraddress) {
this.customeraddress = customeraddress;
}
public Simdetails getSimdetails() {
return simdetails;
}
public void setSimdetails(Simdetails simdetails) {
this.simdetails = simdetails;
}
}
Customer.java
package com.jpa.Proj.Entities;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
public class Customer {
#Id
String uniqueIdNumber;
#DateTimeFormat(pattern="yyyy-MM-dd")
Date dateOfBirth;
String emailAddress;
String firstName;
String lastName;
String idType;
#OneToOne(cascade= CascadeType.ALL)
#JoinColumn(name="addressId")
Customeraddress customeraddress;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "simId")
Simdetails simdetails;
public String getUniqueIdNumber() {
return uniqueIdNumber;
}
public Customer(String uniqueIdNumber, Date dateOfBirth, String emailAddress, String firstName, String lastName,
String idType, Customeraddress customeraddress, Simdetails simdetails) {
super();
this.uniqueIdNumber = uniqueIdNumber;
this.dateOfBirth = dateOfBirth;
this.emailAddress = emailAddress;
this.firstName = firstName;
this.lastName = lastName;
this.idType = idType;
this.customeraddress = customeraddress;
this.simdetails = simdetails;
}
#Override
public String toString() {
return "Customer [uniqueIdNumber=" + uniqueIdNumber + ", dateOfBirth=" + dateOfBirth + ", emailAddress="
+ emailAddress + ", firstName=" + firstName + ", lastName=" + lastName + ", idType=" + idType
+ ", customeraddress=" + customeraddress + ", simdetails=" + simdetails + "]";
}
public Customer() {
super();
}
public void setUniqueIdNumber(String uniqueIdNumber) {
this.uniqueIdNumber = uniqueIdNumber;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
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 String getIdType() {
return idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
public Customeraddress getCustomeraddress() {
return customeraddress;
}
public void setCustomeraddress(Customeraddress customeraddress) {
this.customeraddress = customeraddress;
}
public Simdetails getSimdetails() {
return simdetails;
}
public void setSimdetails(Simdetails simdetails) {
this.simdetails = simdetails;
}
}
CustomerRepo.java
package com.jpa.Proj.Repos;
import java.util.Date;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;
import com.jpa.Proj.DTOs.CustomerDTO;
import com.jpa.Proj.Entities.Customer;
import com.jpa.Proj.Entities.Simdetails;
import com.jpa.Proj.Entities.Simoffers;
#Service
public interface CustomerRepo extends JpaRepository<Customer,Integer>{
#Query("SELECT c from Customer c WHERE c.emailAddress=:cemail AND c.dateOfBirth =:cdob")
Customer findByEmailAdressAndDob(#Param("cemail") String firstName,#Param("cdob") Date lastName);
#Query("Select c from Customer c Where c.uniqueIdNumber=:cun")
Customer findByID(#Param("cun") String un);
}
Following is my api:
public class Validatebasicdetailsapi {
#Autowired
CustomerRepo crepo;
#PostMapping
public CustomerDTO validatebasicdetails(#RequestBody CustomerDTO cdto) {
System.out.println(cdto);
Customer cdt= crepo.findByEmailAdressAndDob(cdto.getEmailAddress(),cdto.getDateOfBirth());
System.out.println("Customer="+cdt);
// System.out.println("date recieved="+cdto.getDateOfBirth());
return new CustomerDTO();
}
}

Cannot get Java #StoredProcedure to work, could not prepare statement

Hi,
I having problem with #StoredProcedureQuery just getting the error "could not prepare statement"? I am not sure why storedprocedure will not run , just keep getting this error:
"Caused by: org.h2.jdbc.JdbcSQLException: Function "SP_ARCHIVE_OLD_BOOKS" not found; SQL statement: call sp_archive_old_books(?,?) [90022-193]"
Named parameters are used for a callable statement, but database metadata indicates named parameters are not supported
#Entity
#Cacheable(value = true)
#Table(name = "Book")
#NamedStoredProcedureQuery(name = "archiveOldBooks", procedureName = "sp_archive_books",
parameters = {
#StoredProcedureParameter(name = "archiveDate", mode = ParameterMode.IN, type = Date.class),
#StoredProcedureParameter(name = "warehouse", mode = ParameterMode.IN, type = String.class),
#StoredProcedureParameter(name = "maxBookArchived", mode = ParameterMode.INOUT, type = Integer.class)
})
#NamedQuery(name = FIND_ALL_BOOKS, query = "select b from Book b")
#SequenceGenerator(name = "SEQ_BOOK", initialValue = 50)
public class Book {
public static final String FIND_ALL_BOOKS = "book.findAllBooks";
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQ_BOOK")
private int id;
#NotNull
#Min(1)
private Integer quantity;
#NotNull
#AllItemTypes
#Enumerated(EnumType.STRING)
private ItemType itemType;
#NotNull
#Title
private String title;
#NotNull
#Price
private Float price;
#NotNull
#Description
private String description;
#NotNull
#Isbn
private String isbnNumber;
#NotNull
#InitDate
private Date initDate;
#NotNull(message = "Invalid illustration is set to null")
private Boolean illustrations;
#NotNull
#PageNumber
private Integer numberOfPages;
#NotNull
#Version
#Min(1)
private Integer version;
#NotNull
#Author
private String author;
#NotNull
#Min(1519)
private Integer year;
// ======================================
// = Constructors =
// ======================================
public Book(){
}
public Book(Integer quantity, ItemType itemType, String title, Float price, String description, String isbnNumber, Date initDate, Boolean illustrations, Integer numberOfPages, Integer version, String author, Integer year) {
this.quantity = quantity;
this.itemType = itemType;
this.title = title;
this.price = price;
this.description = description;
this.isbnNumber = isbnNumber;
this.initDate = initDate;
this.illustrations = illustrations;
this.numberOfPages = numberOfPages;
this.version = version;
this.author = author;
this.year = year;
}
public static String getFindAllBooks() {
return FIND_ALL_BOOKS;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public ItemType getItemType() {
return itemType;
}
public void setItemType(ItemType itemType) {
this.itemType = itemType;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getIsbnNumber() {
return isbnNumber;
}
public void setIsbnNumber(String isbnNumber) {
this.isbnNumber = isbnNumber;
}
public Date getInitDate() {
return initDate;
}
public void setInitDate(Date initDate) {
this.initDate = initDate;
}
public Boolean getIllustrations() {
return illustrations;
}
public void setIllustrations(Boolean illustrations) {
this.illustrations = illustrations;
}
public Integer getNumberOfPages() {
return numberOfPages;
}
public void setNumberOfPages(Integer numberOfPages) {
this.numberOfPages = numberOfPages;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
#Override
public String toString() {
return "Book{" +
"id=" + id +
", quantity=" + quantity +
", itemType=" + itemType +
", title='" + title + '\'' +
", price=" + price +
", description='" + description + '\'' +
", isbnNumber='" + isbnNumber + '\'' +
", initDate=" + initDate +
", illustrations=" + illustrations +
", numberOfPages=" + numberOfPages +
", version=" + version +
", author='" + author + '\'' +
", year=" + year +
'}';
}
}
public abstract class AbstractPeristEntityClass {
protected static EntityManagerFactory emf = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
protected EntityManager em;
protected EntityTransaction tx;
#Before
public void initEntityManager() throws Exception {
em = emf.createEntityManager();
tx = em.getTransaction();
}
#After
public void closeEntityManager() throws SQLException {
if (em != null) em.close();
}
protected Long getRandomId() {
return Math.abs(new Random().nextLong());
}
}
public interface Constants {
String PERSISTENCE_UNIT_NAME = "TEST";
}
public class Book_v2_IT extends AbstractPeristEntityClass {
#Test
public void shouldCallANamedStoredProcedureQuery() throws Exception {
StoredProcedureQuery query = em.createNamedStoredProcedureQuery("archiveOldBooks");
// Set the parameters and execute
query.setParameter("archiveDate", new Date());
query.setParameter("maxBookArchived", 1000);
query.execute();
}
#Test
public void shouldCallAStoredProcedureQuery() throws Exception {
StoredProcedureQuery query = em.createStoredProcedureQuery("sp_archive_old_books");
query.registerStoredProcedureParameter("archiveDate", Date.class, ParameterMode.IN);
query.registerStoredProcedureParameter("maxBookArchived", Integer.class, ParameterMode.IN);
// Set the parameters and execute
query.setParameter("archiveDate", new Date());
query.setParameter("maxBookArchived", 1000);
query.execute();
}
}

Could not deserialize - POJO file error

Using Netbeans 'Create mapping & POJO files from Database' I am receiving this error:
INFO: HHH000327: Error performing load command : org.hibernate.type.SerializationException: could not deserialize
org.hibernate.type.SerializationException: could not deserialize
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:262)
at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:306)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:155)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:130)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:44)
at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:71)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:64)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:263)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:259)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:249)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:334)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2969)
at org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl.loadFromResultSet(EntityReferenceInitializerImpl.java:324)
at org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl.hydrateEntityState(EntityReferenceInitializerImpl.java:251)
at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.readRow(AbstractRowReader.java:107)
at org.hibernate.loader.plan.exec.internal.EntityLoadQueryDetails$EntityLoaderRowReader.readRow(EntityLoadQueryDetails.java:255)
at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:129)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:138)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:186)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4120)
at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:502)
at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:467)
at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:212)
at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:145)
at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1066)
at org.hibernate.internal.SessionImpl.immediateLoad(SessionImpl.java:972)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:173)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:285)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185)
at yy.mavenproject2.Bpauser_$$_jvst210_0.getFullName(Bpauser_$$_jvst210_0.java)
at yy.mavenproject2.PP.main(PP.java:29)
Caused by: java.io.StreamCorruptedException: invalid stream header: 786F0607
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:806)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:328)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:318)
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:237)
... 31 more
And here are PP.java:
package yy.mavenproject2;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import yy.mavenproject2.Bpauser;
public class PP {
public static void main(String[] args) {
Session session = null;
try {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build());
session = sessionFactory.openSession();
if (session.isConnected()) {
String number = "1";
Bpauser emp = (Bpauser) session.load(Bpauser.class, number);
System.out.println("ID is " + emp.getId());
System.out.println("Full Name is " + emp.getFullName());
// System.out.println("E-Mail is " + emp.getEmail());
session.close();
} else {
System.out.println("Connection faiied");
}
} catch (HibernateException e) {
e.printStackTrace();
}
}
}
and Bpauser.java:
package yy.mavenproject2;
// Generated Nov 25, 2015 1:43:19 PM by Hibernate Tools 4.3.1
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.persistence.Version;
/**
* Bpauser generated by hbm2java
*/
#Entity
#Table(name = "BPAUSER", schema = "BPA", uniqueConstraints = #UniqueConstraint(columnNames = {"USERNAME", "ACTIVE", "DEACTIVATION_DATE"})
)
public class Bpauser implements java.io.Serializable {
private String id;
private long version;
private Bpauser bpauser;
private String password;
private String region;
private String surName;
private String firstName;
private String department;
private String company;
private String country;
private String branch;
private String fullName;
private String username;
private String email;
private String location;
private String displayName;
private boolean active;
private Serializable modified;
private Boolean ignoreInSync;
private Boolean receiveNewTaskEmail;
private BigDecimal cbdSyncVersion;
private Serializable deactivationDate;
private Set bpausers = new HashSet(0);
public Bpauser() {
}
public Bpauser(String id, boolean active) {
this.id = id;
this.active = active;
}
public Bpauser(String id, Bpauser bpauser, String password, String region, String surName, String firstName, String department, String company, String country, String branch, String fullName, String username, String email, String location, String displayName, boolean active, Serializable modified, Boolean ignoreInSync, Boolean receiveNewTaskEmail, BigDecimal cbdSyncVersion, Serializable deactivationDate, Set bpausers) {
this.id = id;
this.bpauser = bpauser;
this.password = password;
this.region = region;
this.surName = surName;
this.firstName = firstName;
this.department = department;
this.company = company;
this.country = country;
this.branch = branch;
this.fullName = fullName;
this.username = username;
this.email = email;
this.location = location;
this.displayName = displayName;
this.active = active;
this.modified = modified;
this.ignoreInSync = ignoreInSync;
this.receiveNewTaskEmail = receiveNewTaskEmail;
this.cbdSyncVersion = cbdSyncVersion;
this.deactivationDate = deactivationDate;
this.bpausers = bpausers;
}
#Id
#Column(name = "ID", unique = true, nullable = false, length = 1020)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
#Version
#Column(name = "VERSION", nullable = false, precision = 10, scale = 0)
public long getVersion() {
return this.version;
}
public void setVersion(long version) {
this.version = version;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "SUPERIOR_USER_ID")
public Bpauser getBpauser() {
return this.bpauser;
}
public void setBpauser(Bpauser bpauser) {
this.bpauser = bpauser;
}
#Column(name = "PASSWORD", length = 400)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "REGION", length = 12)
public String getRegion() {
return this.region;
}
public void setRegion(String region) {
this.region = region;
}
#Column(name = "SUR_NAME", length = 200)
public String getSurName() {
return this.surName;
}
public void setSurName(String surName) {
this.surName = surName;
}
#Column(name = "FIRST_NAME", length = 200)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "DEPARTMENT", length = 60)
public String getDepartment() {
return this.department;
}
public void setDepartment(String department) {
this.department = department;
}
#Column(name = "COMPANY", length = 200)
public String getCompany() {
return this.company;
}
public void setCompany(String company) {
this.company = company;
}
#Column(name = "COUNTRY", length = 8)
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
#Column(name = "BRANCH", length = 16)
public String getBranch() {
return this.branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
#ManyToOne(fetch = FetchType.LAZY)
#Column(name = "FULL_NAME", length = 400)
public String getFullName() {
return this.fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
#Column(name = "USERNAME", length = 400)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "EMAIL", length = 300)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "LOCATION", length = 20)
public String getLocation() {
return this.location;
}
public void setLocation(String location) {
this.location = location;
}
#Column(name = "DISPLAY_NAME", length = 400)
public String getDisplayName() {
return this.displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
#Column(name = "ACTIVE", nullable = false, precision = 1, scale = 0)
public boolean isActive() {
return this.active;
}
public void setActive(boolean active) {
this.active = active;
}
#Column(name = "MODIFIED")
public Serializable getModified() {
return this.modified;
}
public void setModified(Serializable modified) {
this.modified = modified;
}
#Column(name = "IGNORE_IN_SYNC", precision = 1, scale = 0)
public Boolean getIgnoreInSync() {
return this.ignoreInSync;
}
public void setIgnoreInSync(Boolean ignoreInSync) {
this.ignoreInSync = ignoreInSync;
}
#Column(name = "RECEIVE_NEW_TASK_EMAIL", precision = 1, scale = 0)
public Boolean getReceiveNewTaskEmail() {
return this.receiveNewTaskEmail;
}
public void setReceiveNewTaskEmail(Boolean receiveNewTaskEmail) {
this.receiveNewTaskEmail = receiveNewTaskEmail;
}
#Column(name = "CBD_SYNC_VERSION", scale = 0)
public BigDecimal getCbdSyncVersion() {
return this.cbdSyncVersion;
}
public void setCbdSyncVersion(BigDecimal cbdSyncVersion) {
this.cbdSyncVersion = cbdSyncVersion;
}
#Column(name = "DEACTIVATION_DATE")
public Serializable getDeactivationDate() {
return this.deactivationDate;
}
public void setDeactivationDate(Serializable deactivationDate) {
this.deactivationDate = deactivationDate;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "bpauser")
public Set getBpausers() {
return this.bpausers;
}
public void setBpausers(Set bpausers) {
this.bpausers = bpausers;
}
}
Could you please assist? I can't find why I have the error related to getter getFullName(). Any comments will be very useful.
OK I found the problem myself. DB has type timestamp(6), I had serialized type of variables with those timestamps. So I changed in POJO this serialized type to Date. Solved.

HQL query for the unary table

I have an user_info table as below
As you see the supervisor column refers the same table.
I am using the Netbean for my development. My POJO created the following class
package database.hibernate_pojo;
// Generated May 31, 2013 12:50:13 AM by Hibernate Tools 3.2.1.GA
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
/**
* UserInfo generated by hbm2java
*/
#Entity
#Table(name="user_info"
,catalog="bit_final_year_project"
, uniqueConstraints = #UniqueConstraint(columnNames="user_name")
)
public class UserInfo implements java.io.Serializable {
private Integer userId;
private UserInfo userInfo;
private String userName;
private String firstName;
private String secondName;
private char department;
private String password;
private char privilege;
private int invalidLogin;
private char status;
private String signaturePath;
private Set<Shipping> shippings = new HashSet<Shipping>(0);
private Set<Audit> audits = new HashSet<Audit>(0);
private Set<UserInfo> userInfos = new HashSet<UserInfo>(0);
public UserInfo() {
}
public UserInfo(String userName, String firstName, String secondName, char department, String password, char privilege, int invalidLogin, char status) {
this.userName = userName;
this.firstName = firstName;
this.secondName = secondName;
this.department = department;
this.password = password;
this.privilege = privilege;
this.invalidLogin = invalidLogin;
this.status = status;
}
public UserInfo(UserInfo userInfo, String userName, String firstName, String secondName, char department, String password, char privilege, int invalidLogin, char status, String signaturePath, Set<Shipping> shippings, Set<Audit> audits, Set<UserInfo> userInfos) {
this.userInfo = userInfo;
this.userName = userName;
this.firstName = firstName;
this.secondName = secondName;
this.department = department;
this.password = password;
this.privilege = privilege;
this.invalidLogin = invalidLogin;
this.status = status;
this.signaturePath = signaturePath;
this.shippings = shippings;
this.audits = audits;
this.userInfos = userInfos;
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="user_id", unique=true, nullable=false)
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="supervisor")
public UserInfo getUserInfo() {
return this.userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
#Column(name="user_name", unique=true, nullable=false, length=12)
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column(name="first_name", nullable=false, length=15)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name="second_name", nullable=false, length=15)
public String getSecondName() {
return this.secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
#Column(name="department", nullable=false, length=1)
public char getDepartment() {
return this.department;
}
public void setDepartment(char department) {
this.department = department;
}
#Column(name="password", nullable=false, length=45)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name="privilege", nullable=false, length=1)
public char getPrivilege() {
return this.privilege;
}
public void setPrivilege(char privilege) {
this.privilege = privilege;
}
#Column(name="invalid_login", nullable=false)
public int getInvalidLogin() {
return this.invalidLogin;
}
public void setInvalidLogin(int invalidLogin) {
this.invalidLogin = invalidLogin;
}
#Column(name="status", nullable=false, length=1)
public char getStatus() {
return this.status;
}
public void setStatus(char status) {
this.status = status;
}
#Column(name="signature_path", length=45)
public String getSignaturePath() {
return this.signaturePath;
}
public void setSignaturePath(String signaturePath) {
this.signaturePath = signaturePath;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="userInfo")
public Set<Shipping> getShippings() {
return this.shippings;
}
public void setShippings(Set<Shipping> shippings) {
this.shippings = shippings;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="userInfo")
public Set<Audit> getAudits() {
return this.audits;
}
public void setAudits(Set<Audit> audits) {
this.audits = audits;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="userInfo")
public Set<UserInfo> getUserInfos() {
return this.userInfos;
}
public void setUserInfos(Set<UserInfo> userInfos) {
this.userInfos = userInfos;
}
}
I want to show the name of the supervisor in my application. I have written the SQL command it worked perfectly in the Workbench.
select e.user_name from user_info e, user_info s where e.user_id=s.supervisor
But the issue was when I tried to write it in HQL there is no respective methods were created by the Netbean in UserInfo class.
Can anyone help me out of this issue to find a solution?
I've found the solution for my issue by my own. It's simply object within another object. Thus I need to query the first object, then the second object can be accessed
public Iterator getCustomSupervisor(){
String hqlQuery = "FROM UserInfo";
Query query = session.createQuery(hqlQuery);
while(query.list().iterator().hasNext()){
//the first object
UserInfo ui = (UserInfo) query.list().iterator().next();
//access the second object
System.out.println(ui.getUserInfo().getUserName());
}
}

How to assign value to Address , Country and City

Here is classes
-Person
-User
-City
-Country
-Address
Person has complex properties of (Address),
Address has complex Properties of (Country , City)
Class User inherited from Person class
scenario:-
I want to create a signup view inwhich i want to assign values to Address , country , city. How can i do it.
Below is the detail of classes
public class Person
{
public Person()
{ }
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private Gender gender;
public virtual Gender Gender
{
get { return gender; }
set { gender = value; }
}
private ICollection<ContactNumber> contactNumber;
public virtual ICollection<ContactNumber> ContactNumber
{
get { return contactNumber; }
set { contactNumber = value; }
}
private Address address;
public virtual Address Address
{
get { return address; }
set { address = value; }
}
private DateTime dateOfBirth;
public DateTime DateOfBirth
{
get { return dateOfBirth; }
set { dateOfBirth = value; }
}
private string picture;
public string Picture
{
get { return picture; }
set { picture = value; }
}
}
public class User : Person
{
public User() : base()
{ }
private ICollection<Role> roles;
public virtual ICollection<Role> Roles
{
get { return roles; }
set { roles = value; }
}
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string email;
[Required()]
[RegularExpression(#"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*")]
[Display(Name = "Email Address")]
public string Email
{
get { return email; }
set { email = value; }
}
private string loginId;
[Required()]
[Display(Name = "Login")]
public string LoginId
{
get { return loginId; }
set { loginId = value; }
}
private string password;
[Required()]
[Display(Name = "Password")]
[DataType(DataType.Password)]
public string Password
{
get { return password; }
set { password = value; }
}
private string repassword;
[Required()]
[Display(Name = "Confirm Password")]
[Compare("Password")]
public string Repassword
{
get { return repassword; }
set { repassword = value; }
}
private string secretQuestion;
[Required()]
[Display(Name = "Secret Question")]
public string SecretQuestion
{
get { return secretQuestion; }
set { secretQuestion = value; }
}
private string secretAnswer;
[Required()]
[Display(Name = "Answer")]
public string SecretAnswer
{
get { return secretAnswer; }
set { secretAnswer = value; }
}
private string photoUrl;
[Display(Name = "Image")]
public string PhotoUrl
{
get { return photoUrl; }
set { photoUrl = value; }
}
}
public class Country
{
public Country()
{ }
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
//private string flagUrl;
}
public class City
{
public City()
{ }
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private Country country;
public virtual Country Country
{
get { return country; }
set { country = value; }
}
}
Thanx in Advance.
If you right click on your action method for your signup page in your controller and select Add View In the dialog that appears you can choose to make the view strongly typed. Select your User class and visual studio will scaffold a lot of the code needed.
If you need more help in working with MVC here is a good place to start.