UserBean Class
#Entity
#Table(name="users")
public class UserBean {
#Id
#GeneratedValue(strategy =GenerationType.AUTO)
#Column(name="ID")
private Integer id;
#Column(name = "NAME")
private String name;
#Column(name = "EMAIL")
private String email;
#Column(name = "AGE")
private int age;
/**
* #return the id
*/
public Integer getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the email
*/
public String getEmail() {
return email;
}
/**
* #param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* #return the age
*/
public int getAge() {
return age;
}
/**
* #param age the age to set
*/
public void setAge(int age) {
this.age = age;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("UserBean [id=").append(id).append(", name=")
.append(name).append(", email=").append(email).append(", age=")
.append(age).append("]");
return builder.toString();
}
}
I am getting ORA:02289 Sequence doesn't exist
Here is hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<mapping class="com.abc.bean.UserBean" />
</session-factory>
</hibernate-configuration>
Dispatcher package scan
<context:component-scan base-package="com.abc.controller" />
<context:component-scan base-package="com.abc.dao.impl" />
<mvc:annotation-driven />
I have tried the same thing in another laptop and it worked, what is causing the problem? Earlier, I tried to generate a sequence but it didn't worked well
Sql command executed:
create table users(id int primary key,name varchar(20),email varchar(20),age int);
hibernate use sequence for oracle db if you use GenerationType.AUTO (default global sequence name hibernate_sequence) . You should create sequence and configure it in entity mapping , like :
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_generator")
#SequenceGenerator(name="user_generator", sequenceName = "user_seq")
#Column(name="ID",allocationSize = 1)
private Integer id;
Which version of Oracle you using? As per my knowledge Auto increment not supported in 11g but supports in 12c..
Related
When creating my contact DAO and related classes, I am getting the following error:
The query returns some columns [mContactId, mAddress, mPostcode, mCity, mCountry, mAddressType]
which are not used by org.linphone.contacts.managementWS.ContactWithAddresses. You can use
#ColumnInfo annotation on the fields to specify the mapping.
org.linphone.contacts.managementWS.ContactWithAddresses has some fields [mName, mSurname,
mFullName, mCompany, mNote, mIsBlocked] which are not returned by the query. If they are not
supposed to be read from the result, you can mark them with #Ignore annotation. You can suppress
this warning by annotating the method with #SuppressWarnings(RoomWarnings.CURSOR_MISMATCH).
Columns returned by the query: id, mContactId, mAddress, mPostcode, mCity, mCountry,
mAddressType. Fields in org.linphone.contacts.managementWS.ContactWithAddresses: id, mName,
mSurname, mFullName, mCompany, mNote, mIsBlocked.
In my ContactsDao:
#Query("SELECT * FROM contacts_table")
List<Contact> getAll();
#Transaction
#Query("SELECT * FROM phone_numbers_table")
List<ContactWithNumbers> getContactsWithPhoneNumbers();
ContactsWithNumbers.java:
#Embedded public Contact contact;
#Relation(parentColumn = "id", entityColumn = "mContactId", entity = PhoneNumbers.class)
public List<PhoneNumbers> numbers;
And below is my Contact.java:
#Entity(tableName = "contacts_table")
public class Contact {
// TODO - members should be private, not public. Changed to workaround error.
#PrimaryKey(autoGenerate = true)
public int id;
/* String resource ID for the user name */
#SerializedName("first_name")
public String mName;
/* String resource ID for the user surname */
#SerializedName("last_name")
public String mSurname;
/* String resource ID for the user's full name */
#SerializedName("full_name")
public String mFullName;
/* String resource ID for the user company */
#SerializedName("company")
public String mCompany;
/* String resource ID for the user's phone number(s) */
/** String resource ID for the user's note */
#SerializedName("note")
public String mNote;
#SerializedName("blocked")
public boolean mIsBlocked;
/**
* #param firstName
* #param lastName
* #param fullName
* #param company
* #param note
* #param isBlocked
*/
#Ignore
public Contact(
String firstName,
String lastName,
String fullName,
String company,
String note,
boolean isBlocked) {
super();
this.mName = firstName;
this.mSurname = lastName;
this.mFullName = fullName;
this.mCompany = company;
this.mNote = note;
this.mIsBlocked = isBlocked;
}
public Contact(String name, String surname, String company, String note, boolean isBlocked) {
this.mName = name;
this.mSurname = surname;
this.mCompany = company;
this.mNote = note;
this.mIsBlocked = isBlocked;
}
public int getId() {
return id;
}
public String getmName() {
return mName;
}
public String getmSurname() {
return mSurname;
}
public String getmFullName() {
return mName + " " + mSurname;
}
public String getmCompany() {
return mCompany;
}
public String getmNote() {
return mNote;
}
public boolean getmIsBlocked() {
return mIsBlocked;
}
}
It is quite likely that I have not fully grasped the concept of Room one-to-many relations, but what exactly am I doing wrong here and getting that warning?
It's say very clear: You can use #ColumnInfo annotation on the fields to specify the mapping.
Change your code like this:
#NonNull
#PrimaryKey
#ColumnInfo(name = "id")
private String id;
More at codelab: https://codelabs.developers.google.com/codelabs/android-room-with-a-view/#0
When using the JPA Extension to scan an entity that includes #Embedded objects the $metadata is created correctly with ComplexTypes. However, when retrieving the entity I receive a ClassCastException:
org.apache.olingo.odata2.core.edm.provider.EdmComplexTypeImplProv
cannot be cast to org.apache.olingo.odata2.api.edm.EdmSimpleType
Class:
org.apache.olingo.odata2.jpa.processor.core.access.data.JPAEntityParse
Here is the entity code I'm using:
#Entity
public class BORROWER {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Embedded
protected BORROWER_DETAIL borrower_DETAIL;
#Embedded
protected NAME name;
#ManyToOne
protected DEAL deal;
//Mark transient to force orika to skip
#Transient
public DEAL getDeal() {
return deal;
}
public void setDeal(DEAL deal) {
this.deal = deal;
}
/**
* Gets the value of the borrower_DETAIL property.
*
* #return
* possible object is
*
*
*/
public BORROWER_DETAIL getBORROWER_DETAIL() {
return borrower_DETAIL;
}
/**
* Sets the value of the borrower_DETAIL property.
*
* #param value
* allowed object is
*
*
*/
public void setBORROWER_DETAIL(BORROWER_DETAIL value) {
this.borrower_DETAIL = value;
}
public NAME getName() {
return name;
}
public void setName(NAME name) {
this.name = name;
}
public long getId() {
return id;
}
}
Seeing the comment regarding getter/setters being the source of the issue on this bug ticket (also I borrowed parts of the write up for the question):
https://issues.apache.org/jira/browse/OLINGO-948
I updated the getter and setter method signatures for borrower_DETAIL, and I'm no longer getting the error. Here is the updated entity code that is working for me:
#Entity
public class BORROWER {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Embedded
protected BORROWER_DETAIL borrower_DETAIL;
#Embedded
protected NAME name;
#ManyToOne
protected DEAL deal;
//Mark transient to force orika to skip
#Transient
public DEAL getDeal() {
return deal;
}
public void setDeal(DEAL deal) {
this.deal = deal;
}
public BORROWER_DETAIL getBorrower_DETAIL() {
return borrower_DETAIL;
}
public void setBorrower_DETAIL(BORROWER_DETAIL borrower_DETAIL) {
this.borrower_DETAIL = borrower_DETAIL;
}
public NAME getName() {
return name;
}
public void setName(NAME name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
My DTO is being stored using JPA Hibernate and I'm able to store the other fields but having trouble trying to store this relationship for the user. The userRoleSet HashSet has ENUMs that represent what roles that user has. Some users with have no roles while someone will have 1 to 3 roles. Each role is different. How would I got about representing this in my database and using JPA? At the moment, the #ManyToMany doesn't work, I miss be missing something else? Essentially, I need to be able to query that specific user in the database and have it return the roles that is assigned to that user.
UserType Enums
public enum UserType
{
ALPHA,BRAVO,CHARLIE
}
Default User DTO JPA
#Entity
#Table(name = "users")
public class DefaultUser implements Serializable
{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "user_id")
private long user_id;
#Column(name = "user_name")
private String user_name;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "password")
private String password;
#ManyToMany
private Set<UserType> userRoleSet = new HashSet<UserType>();
/**
* #return the userTypes
*/
public Set<UserType> getUserTypes()
{
return userRoleSet;
}
/**
*
* #param userTypes
* the userTypes to set
*/
public void setUserTypes(Set<UserType> userTypes)
{
this.userRoleSet = userTypes;
}
/**
* #return the user_id
*/
public long getUser_id()
{
return user_id;
}
/**
* #return the user_name
*/
public String getUser_name()
{
return user_name;
}
/**
* #return the firstName
*/
public String getFirstName()
{
return firstName;
}
/**
* #return the lastName
*/
public String getLastName()
{
return lastName;
}
/**
* #return the password
*/
public String getPassword()
{
return password;
}
/**
* #param user_id
* the user_id to set
*/
public void setUser_id(long user_id)
{
this.user_id = user_id;
}
/**
* #param user_name
* the user_name to set
*/
public void setUser_name(String user_name)
{
this.user_name = user_name;
}
/**
* #param firstName
* the firstName to set
*/
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
/**
* #param lastName
* the lastName to set
*/
public void setLastName(String lastName)
{
this.lastName = lastName;
}
/**
* #param password
* the password to set
*/
public void setPassword(String password)
{
this.password = password;
}
}
The #ManyToMany annotation is used to map an association between two entities. For collections of simple types, the annotation to use is #ElementCollection.
PS: you always read and post the complete and exact error message you get when something "doesn't work".
I am trying to update a table row using the session.saveOrUpdate() method in Hibernate.
However, it is unable to update the row and tries to save it by producing an insert statement. This insert does not work due to a few non-nullable fields in my DB.
I am able to retrieve the Id of the object to be saved at the DAO layer, so I am not able to understand why it doesn't just update the corresponding row in the DB table.
Bean Class: (BaseEntityBean has the Id, CreatedBy, etc.)
public class EmployeeMasterBean extends BaseEntityBean {
/**
*
*/
private static final long serialVersionUID = 1L;
#Column(name = "FirstName", nullable = false)
private String firstName;
#Column(name = "LastName", nullable = false)
private String lastName;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "Dob", insertable = true, updatable = true, nullable = false)
private Date dateOfBirth;
#Column(name = "Email", length = 100)
private String email;
#Column(name = "PhoneNumber", nullable = false)
private String phoneNumber;
#Column(name = "Address1", nullable = false)
private String address1;
#Column(name = "Type", nullable = false)
private Short employeeType;
#Column(name = "Gender", nullable = false)
private Short gender;
/**
* #return the firstName
*/
public final String getFirstName() {
return firstName;
}
/**
* #param firstName the firstName to set
*/
public final void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* #return the lastName
*/
public final String getLastName() {
return lastName;
}
/**
* #param lastName the lastName to set
*/
public final void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* #return the dateOfBirth
*/
public final Date getDateOfBirth() {
return dateOfBirth;
}
/**
* #param dateOfBirth the dateOfBirth to set
*/
public final void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
/**
* #return the email
*/
public final String getEmail() {
return email;
}
/**
* #param email the email to set
*/
public final void setEmail(String email) {
this.email = email;
}
/**
* #return the phoneNumber
*/
public final String getPhoneNumber() {
return phoneNumber;
}
/**
* #param phoneNumber the phoneNumber to set
*/
public final void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
/**
* #return the address1
*/
public final String getAddress1() {
return address1;
}
/**
* #param address1 the address1 to set
*/
public final void setAddress1(String address1) {
this.address1 = address1;
}
/**
* #return the employeeType
*/
public final Short getEmployeeType() {
return employeeType;
}
/**
* #param employeeType the employeeType to set
*/
public final void setEmployeeType(Short employeeType) {
this.employeeType = employeeType;
}
/**
* #return the gender
*/
public final Short getGender() {
return gender;
}
/**
* #param gender the gender to set
*/
public final void setGender(Short gender) {
this.gender = gender;
}
}
DAO Method:
public EmployeeMasterBean saveOrUpdateEmployee(EmployeeMasterBean employeeMasterBean) throws Exception{
Session session = null;
Transaction tx = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
tx = session.beginTransaction();
session.saveOrUpdate(employeeMasterBean);
tx.commit();
} finally {
session.close();
}
return employeeMasterBean;
}
Eclipse debugger exceptions thrown are:
could not insert: [com.indven.gpil.hrd.entity.EmployeeMasterBean]
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'CreatedBy' cannot be null
As the error message say, the database has a column createdby which can't be null.
When you called saveOrUpdate() someone has set this property to null so the update isn't possible.
I think CreatedBy column is present in DB table as notnull but your bean does not have this column mapped, hence a null value is sent when you do a saveOrUpdate, which causes Above exception to be thrown.
Either add a mapping to CreatedBy in your bean with some default value and let trigger etc can update the default value. Or if you can change the column to be nullable in Database
The bean did not have the rowVersion property (for optimistic locking) set, and hence by default it was null. Hibernate thus interpreted this as a new record, and kept saving it.
I fixed it by storing the row version in my Value Object and the corresponding Bean whenever I attempted to save or update any records.
we can add the following to jsp form to match with entity PK (id),
<form:hidden path="id" />
I want to insert data into a table that is associated with another table in a relationship ManyToMany. When I insert the data, it is inserted into the table but the association with the other data that is in the second table is not. This is a Java EE application using JSF2+Spring+Hibernate.
Here is the entity:
#Entity
#Table(name="USER")
public class User {
private int id;
private String nom;
private Set<Formation> mesformations;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "USER_ID")
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the nom
*/
#Column(name="NOM",length=50)
public String getNOM() {
return nom;
}
/**
* #param nom the nom to set
*/
public void setNom(String nom) {
this.nom = nom;
}
/**
* #return the mesFormations
*/
#ManyToMany
#Cascade({CascadeType.SAVE_UPDATE, CascadeType.MERGE})
#JoinTable(name = "USER_FORM",
joinColumns = #JoinColumn(name = "user_id",
referencedColumnName = "USER_ID"),
inverseJoinColumns = #JoinColumn(name = "form_id", referencedColumnName = "ID"))
public Set<Formation> getMesFormations() {
return mesFormations;
}
/**
* #param mesFormations the mesFormations to set
*/
public void setMesFormations(Set<Formation> mesFormations) {
this.mesFormations = mesFormations;
}
public void addToFormation(Formation formation) {
if(mesFormation==null)
{
mesFormations=new HashSet<Formation>();
}
mesFormations.add(formation);
}
.....
}
Formation.java
#Entity
#Table(name="Foramtion")
public class Formation {
private int id;
private String nomFormation;
private int nombreMatiere;
private Set<User> mesUsers;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID")
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the mesUsers
*/
#ManyToMany(mappedBy = "mesFormations",fetch=FetchType.LAZY)
#Cascade({CascadeType.SAVE_UPDATE, CascadeType.MERGE})
public Set<User> getMesUsers() {
return mesUsers;
}
/**
* #param mesUsers the mesUsers to set
*/
public void setMesUsers(Set<User> mesUsers) {
this. mesUsers = mesUsers;
}
/**
* #return the nomFormation
*/
#Column(name="NOM_FORMATION",length=50,unique=true)
public String getNomFormation() {
return nomForamtion;
}
/**
* #param nomFormation the nomForamtion to set
*/
public void setNomForamtion(String nomForamtion) {
this.nomForamtion = nomForamtion;
}
/**
* #return the nombreMatiere
*/
public int getNombreMatiere() {
return nombreMatiere;
}
/**
* #param nombreMatiere the nombreMatiere to set
*/
public void setNombreMatiere(int nombreMatiere) {
this.nombreMatiere = nombreMatiere;
}
public void addToUser(User user) {
if(mesUser==null)
{
mesUsers=new HashSet<User>();
}
mesUsers.add(user);
user.addToFormation(this);
}
public void removeFromUser(User user) {
this.getMesUsers().remove(user);
user.getMesUsers().remove(this);
}
}
the method of the DAO layer which allows for the persistence of a user
public User enregistrer(User user) {
// TODO Auto-generated method stub
this.getSession().beginTransaction();
this.getSession().persist(user);
this.getSession().beginTransaction().commit();
return Entity ;
}
the method of the service layer that allows to call the save method of the dao layer
public User persistUser(User user, List<Integer> idList){
for(Integer id : idList){
Formation form = iformationDao.findById(id);
form.addToUser(user);
}
return iuserDao.enregistrer(user);
thank for answering
It looks to me like you have your CascadeTypes set to:
#Cascade({CascadeType.SAVE_UPDATE, CascadeType.MERGE})
yet you are calling:
this.getSession().persist(user);
I think you will need to add CascadeType.PERSIST to your #Cascade annotation to get the behavior you desire.
change from
public User enregistrer(User user) {
// TODO Auto-generated method stub
this.getSession().beginTransaction();
this.getSession().persist(user);
this.getSession().beginTransaction().commit();
return Entity ;
}
to
public User enregistrer(User user) {
// TODO Auto-generated method stub
Transaction tx = this.getSession().beginTransaction();//change
this.getSession().persist(user);
tx.commit();//change
return Entity ;
}