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());
}
}
Related
In my spring boot application I have user model, type model and user_type. Here a join table is created in the user model as user_type.
Model in maven project with jpa :
package com.example.pharmanic.model;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.*;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
#Entity
#Table( name = "users",
uniqueConstraints = {
#UniqueConstraint(columnNames = "username"),
#UniqueConstraint(columnNames = "email")
})
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank
#Size(max = 20)
private String username;
#NotBlank
#Size(max = 50)
#Email
private String email;
#NotBlank
#Size(max = 120)
private String password;
**#ManyToMany(fetch = FetchType.LAZY)
#JoinTable( name = "user_roles",
joinColumns = #JoinColumn(name = "user_id") ,
inverseJoinColumns = #JoinColumn(name = "role_id")
)**
private Set<Role> roles = new HashSet<>();
public User() {
}
public User(String username, String email, String password) {
this.username = username;
this.email = email;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
The join table user_role has two columns; user_id & role_id.
I want to add an extra column to user_role table to save more data relevant to user_role. A type String column should be added to the user_role table.
I wrote two controller class in spring application called player and team and I want join this model classes for connect sql database and I write code but it give me error so please help me to resolve that I'm sure problem happen in below two files and my other dependencies and database connection working well
my Team class
package com.withAngular.team;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.beans.factory.annotation.Autowired;
import com.withAngular.demo.player.Player;
#Entity
#Table(name = "team")
public class Team {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "team")
private String team;
#Column(name = "description")
private String description;
#Column(name = "owner")
private String owner;
#Column(name = "total_played")
private int totalPlayed;
#Column(name = "total_won")
private int totalWon;
#Column(name = "total_lost")
private int totalLost;
#Column(name = "no_result")
private int noResult;
#OneToMany
(mappedBy = "team", cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
private List<Player> players = new ArrayList<>();
public Team(int id, String name, String description, String owner, int totalplayed, int totalwon, int totallost, int noresult) {
this.setId(id);
this.setDescription(description);
this.setOwner(owner);
this.setTotalPlayed(totalplayed);
this.setTotalWon(totalwon);
this.setTotalLost(totallost);
this.setNoResult(noresult);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTeam() {
return team;
}
public void setTeam(String team) {
this.team = team;
}
public List<Player> getPlayers() {
return players;
}
public void setPlayers(List<Player> players) {
this.players = players;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public int getTotalPlayed() {
return totalPlayed;
}
public void setTotalPlayed(int totalPlayed) {
this.totalPlayed = totalPlayed;
}
public int getTotalWon() {
return totalWon;
}
public void setTotalWon(int totalWon) {
this.totalWon = totalWon;
}
public int getTotalLost() {
return totalLost;
}
public void setTotalLost(int totalLost) {
this.totalLost = totalLost;
}
public int getNoResult() {
return noResult;
}
public void setNoResult(int noResult) {
this.noResult = noResult;
}
}
my Player class
package com.withAngular.demo.player;
import javax.persistence.Column;
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 com.withAngular.team.Team;
#Entity
// #Table(name=PLAYER) when table name different from the class name
public class Player {
#Id // primary key
#GeneratedValue(strategy = GenerationType.AUTO) // auto increment
private int id;
// #Column(name = "PlayerName") when db table column name different from the
// property name assigned below
private String playerName;
private String preference;
#Column(name= "match_played")
private int matchPlayed;
private int runs;
private int wickets;
#Column(name= "highest_score")
private int highestScore;
#Column(name="best_wicket")
private String bestWicket;
private int fifties;
private int centuries;
private int thirties;
private int catches;
private int stumpings;
private int fours;
private int sixes;
#Column(name = "strike_rate")
private double strikeRate;
private double average;
#ManyToOne(targetEntity = Team.class)
#JoinColumn(name= "team_id")
private Team team;
// getters and setters
public Player(int id, String playername, String preference, int matchplayed, int runs, int wickets, int highestscore, String bestWicket, int fifties, int centuries, int thirties, int caches, int stumpings,int fours, int sixes, double strikerate, double average) {
// TODO Auto-generated constructor stub
this.setId(id);
this.setPlayerName(playername);
this.setPreference(preference);
this.setMatchPlayed(matchplayed);
this.setRuns(runs);
this.setWickets(wickets);
this.setHighestScore(highestscore);
this.setBestWicket(bestWicket);
this.setFifties(fifties);
this.setCenturies(centuries);
this.setThirties(thirties);
this.setCatches(caches);
this.setStumpings(stumpings);
this.setFours(fours);
this.setSixes(sixes);
this.setStrikeRate(strikerate);
this.setAverage(average);
}
public int getId() {
return id;
}
public String getPreference() {
return preference;
}
public void setPreference(String preference) {
this.preference = preference;
}
public int getMatchPlayed() {
return matchPlayed;
}
public void setMatchPlayed(int matchPlayed) {
this.matchPlayed = matchPlayed;
}
public int getRuns() {
return runs;
}
public void setRuns(int runs) {
this.runs = runs;
}
public int getWickets() {
return wickets;
}
public void setWickets(int wickets) {
this.wickets = wickets;
}
public int getHighestScore() {
return highestScore;
}
public void setHighestScore(int highestScore) {
this.highestScore = highestScore;
}
public String getBestWicket() {
return bestWicket;
}
public void setBestWicket(String bestWicket) {
this.bestWicket = bestWicket;
}
public int getFifties() {
return fifties;
}
public void setFifties(int fifties) {
this.fifties = fifties;
}
public int getCenturies() {
return centuries;
}
public void setCenturies(int centuries) {
this.centuries = centuries;
}
public int getThirties() {
return thirties;
}
public void setThirties(int thirties) {
this.thirties = thirties;
}
public int getCatches() {
return catches;
}
public void setCatches(int catches) {
this.catches = catches;
}
public int getStumpings() {
return stumpings;
}
public void setStumpings(int stumpings) {
this.stumpings = stumpings;
}
public int getFours() {
return fours;
}
public void setFours(int fours) {
this.fours = fours;
}
public int getSixes() {
return sixes;
}
public void setSixes(int sixes) {
this.sixes = sixes;
}
public double getStrikeRate() {
return strikeRate;
}
public void setStrikeRate(double strikeRate) {
this.strikeRate = strikeRate;
}
public double getAverage() {
return average;
}
public void setAverage(double average) {
this.average = average;
}
public Team getTeam() {
return team;
}
public void setTeam(Team team) {
this.team = team;
}
public void setId(int id) {
this.id = id;
}
public String getPlayerName() {
return playerName;
}
public void setPlayerName(String playerName) {
this.playerName = playerName;
}
}
and after run as spring boot app it give me below error
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 org.hibernate.AnnotationException: #OneToOne or #ManyToOne on com.withAngular.demo.player.Player.team references an unknown entity: com.withAngular.team.Team
It is a very simple problem, You need to put both the entity classes in same package and that package should be either the package which holds the main application class that is annotated with
#SpringBootApplication
Or any of the sub package of parent package.
Eg: If package of your parent class is com.withAngular than put the Team and Player class also in the same package.
Change package com.withAngular.team; to package com.withAngular; in Team class.
Change package com.withAngular.demo.player; to package com.withAngular; in Player class.
Use the Annotation EnableJpaRepositories in your class annotated with #SpringBootApplication and set the
attribute basePackages to a common package.
So in your case com.withAngular.
#EnableJpaRepositories(basePackages="com.withAngular")
But it is better to moven entities in the same subpackage not in the "root" package of your application
Student Model--
Which code I must write to set photo type in the Student?
package mh.st.model;
import java.sql.Date;
import java.time.LocalDate;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.scene.image.Image;
public class Student {
private IntegerProperty id;
private StringProperty firstName;
private StringProperty lastName;
private StringProperty fatherName;
private IntegerProperty ID;
private StringProperty phone;
private StringProperty birthday;
private ObjectProperty<Image>photo;
public Student()
{
}
public Student(int id,String firstName,String lastName,String fatherName,int ID,String phone,String birthday,Object photo)
{
this.id=new SimpleIntegerProperty(id);
this.firstName=new SimpleStringProperty(firstName);
this.lastName=new SimpleStringProperty(lastName);
this.fatherName=new SimpleStringProperty(fatherName);
this.ID=new SimpleIntegerProperty(ID);
this.phone=new SimpleStringProperty(phone);
this.birthday=new SimpleStringProperty(birthday);
}
public IntegerProperty getId() {
return id;
}
public StringProperty getFatherName() {
return fatherName;
}
public void setFatherName(String fatherName) {
this.fatherName =new SimpleStringProperty(fatherName);
}
public StringProperty getFirstName() {
return firstName;
}
public StringProperty getLastName() {
return lastName;
}
public IntegerProperty getID() {
return ID;
}
public StringProperty getPhone() {
return phone;
}
public StringProperty getBirthday() {
return birthday;
}
public void setFirstName(String firstName) {
this.firstName =new SimpleStringProperty(firstName);
}
public void setLastName(String lastName) {
this.lastName =new SimpleStringProperty(lastName);
}
public void setID(Integer ID) {
this.ID =new SimpleIntegerProperty(ID);
}
public void setPhone(String phone) {
this.phone =new SimpleStringProperty(phone);
}
public void setBirthday(String birthday) {
this.birthday =new SimpleStringProperty(birthday);
}
}
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.
Hi I want to display the bean value inside the text box using struts2 , But its not working ,Please help.
Even I tried to set and get the value from the bean but still not working.
I have attached the output .
Customer.java
package com.java.bean;
public class Customer {
private int id;
private String customerName;
private String cifNumber;
private int idNumber;
private String idCountry;
private String idType;
private int master_id;
private String rmCode;
private String customerCountry;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCifNumber() {
return cifNumber;
}
public void setCifNumber(String cifNumber) {
this.cifNumber = cifNumber;
}
public int getIdNumber() {
return idNumber;
}
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
public String getIdCountry() {
return idCountry;
}
public void setIdCountry(String idCountry) {
this.idCountry = idCountry;
}
public String getIdType() {
return idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
public int getMaster_id() {
return master_id;
}
public void setMaster_id(int master_id) {
this.master_id = master_id;
}
public String getRmCode() {
return rmCode;
}
public void setRmCode(String rmCode) {
this.rmCode = rmCode;
}
public String getCustomerCountry() {
return customerCountry;
}
public void setCustomerCountry(String customerCountry) {
this.customerCountry = customerCountry;
}
}
CustomerSearchActionForam.java
package com.vaannila;
public class CustomerSearchActionForm extends org.apache.struts.action.ActionForm{
private int id;
private String customerName;
private String cifNumber;
private int idNumber;
private String idCountry;
private String idType;
private int master_id;
private String rmCode;
private String customerCountry;
private String message;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getCifNumber() {
return cifNumber;
}
public void setCifNumber(String cifNumber) {
this.cifNumber = cifNumber;
}
public int getIdNumber() {
return idNumber;
}
public void setIdNumber(int idNumber) {
this.idNumber = idNumber;
}
public String getIdCountry() {
return idCountry;
}
public void setIdCountry(String idCountry) {
this.idCountry = idCountry;
}
public String getIdType() {
return idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
public int getMaster_id() {
return master_id;
}
public void setMaster_id(int master_id) {
this.master_id = master_id;
}
public String getRmCode() {
return rmCode;
}
public void setRmCode(String rmCode) {
this.rmCode = rmCode;
}
public String getCustomerCountry() {
return customerCountry;
}
public void setCustomerCountry(String customerCountry) {
this.customerCountry = customerCountry;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
SearchCustomer.java
import javax.servlet.http.HttpServletRequest;
import java.beans.*;
import java.util.List;
import java.util.Iterator;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.util.MessageResources;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.java.bean.Customer;
import com.java.bean.LoginUser;
public class SearchCustomer extends org.apache.struts.action.Action {
#Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
CustomerSearchActionForm customerSearch = (CustomerSearchActionForm) form;
MessageResources msgResource = getResources(request);
String cifNumber_=customerSearch.getCifNumber();
String Result_ = "success";
System.out.println("CIF NUMBER:"+cifNumber_);
SearchCustomer Scust = new SearchCustomer();
List customer=Scust.listCustomers(cifNumber_);
request.setAttribute("customerList",customer);
Iterator iterator = customer.iterator();
if(iterator.hasNext()){
System.out.println("customer found");
customerSearch.setMessage(msgResource.getMessage("msg.customerfound"));
}
else{
System.out.print("Customer Not Found");
customerSearch.setMessage(msgResource.getMessage("error.nocustomerfound"));
}
System.out.println("List of Customers : "+customer);
return mapping.findForward(Result_);
}
public List listCustomers(String cifNumber_){
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
Transaction tx = null;
List customer = null;
try{
tx = session.beginTransaction();
Query sql = session.createQuery("from Customer where cifNumber=:cifNumbervalue");
System.out.println("Query printing "+sql);
sql.setParameter("cifNumbervalue",cifNumber_);
customer = sql.list();
System.out.println("CUSTOMER LIST ITERATION"+customer);
for (Iterator iterator = customer.iterator(); iterator.hasNext();){
Customer cust = (Customer) iterator.next();
String cifNumber=cust.getCifNumber();
String custName=cust.getCustomerName();
System.out.println("----------------------------------------------------------- - -------------------------------------------");
System.out.print("CifNumber: " + cifNumber+" CustomerName :"+custName);
}
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return customer;
}
}
LoginHome.jsp (to display my records from database)
<%#page contentType="text/html"%>
<%#page pageEncoding="UTF-8"%>
<%#taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<div style="color:red">
<html:errors />
</div>
<html:form action="/Login" >
User Name :<html:text name="LoginActionForm" property="userName" />
Password :<html:password name="LoginActionForm" property="passWord" />
<html:submit value="Login" />
</html:form>
</body>
OUTPUT
CifNumber: 10000
CustomerName: JP Morgon
IDNumber: 123321
ID Country: SINGAPORE
RM CODE: E001
CustomerCountry: USA
Customer Details
CIF NUMBER :
CUSTOMER NAME :
ID NUMBER :
ID COUNTRY :
RM CODE :
CUSTOMER COUNTRY :
login