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".
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
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..
I have user login and profile view, I would like the users to have posts. Can someone guide me in the right direction?
I have a user entity:
#Entity
#Table(name = "usr", indexes = { #Index(columnList = "email", unique = true) })
// using usr because in may conflict with the name of the class
public class User {
public static final int EMAIL_MAX = 250;
public static final int NAME_MAX = 50;
/*
* public static enum Role {
*
* UNVERIFIED, BLOCKED, ADMINISTRATOR
*
* }
*/
// primary key long, needs to be annotated with #Id
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
// add columns
#Column(nullable = false, length = EMAIL_MAX)
private String email;
#Column(nullable = false, length = NAME_MAX)
private String name;
// no length, the password will be encrypted to some longer value than the
// user enters
#Column(nullable = false)
private String password;
/*
* //email verification code
*
* #Column(length = 16) private String verificationCode;
*
* public String getVerificationCode() { return verificationCode; }
*
* public void setVerificationCode(String verificationCode) {
* this.verificationCode = verificationCode; }
*
*
* #ElementCollection(fetch = FetchType.EAGER) private Set<Role> roles = new
* HashSet<Role>();
*
*
*
* public Set<Role> getRoles() { return roles; }
*
* public void setRoles(Set<Role> roles) { this.roles = roles; }
*/
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isEditable() {
User loggedIn = MyTools.getSessionUser();
if (loggedIn == null) {
return false;
}
return loggedIn.getId() == id;
}
}
and repo:
public interface UserRepository extends JpaRepository<User, Long> {
// #Query("select u from User u where u.email = ?1")
User findByEmail(String email);
}
now, in order to have posts by that user, do I create a posts entity and repository with #manytoone in post pojo?
I'm trying to make a twitter eventually but first I gotta get users to post. If you know of a good tutorial explaining this then that'd be great.
Create a second entity (java class) e.g. UserPost:
#Entity
#Table(...)
public class UserPost {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private long userId;
...
}
Then add #OneToMany relationship field to User. Cascading, lazy-loading, etc. depends on how you'd use it. It'd look like this inside User:
#OneToMany(cascade={...})
#JoinColumn(name="userId")
private Set<UserPost> posts;
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'm trying to create a #OneToMany relationship in the same entity. Here is a sample code:
#Entity
public class Client extends Model{
private static final long serialVersionUID = 1L;
public Client(String username, String email) {
super();
this.username = username;
this.email = email;
}
#Id
String username;
#Required
String email;
#ManyToOne
Client parent;
#OneToMany(mappedBy="parent")
Set<Client> friends = new HashSet<Client>();
static Finder<String,Client> find = new Finder<String,Client>(String.class, Client.class);
public static void create(Client regUser){
regUser.save();
}
public static Client getByUsername(String username){
return find.byId(username);
}
public void addFriend(Client relatedClient){
this.friends.add(relatedClient);
relatedClient.update();
this.update();
}
/**
* #return the username
*/
public String getUsername() {
return username;
}
/**
* #param username the username to set
*/
public void setUsername(String username) {
this.username = username;
}
/**
* #return the email
*/
public String getEmail() {
return email;
}
/**
* #param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
/**
* #return the friends
*/
public Set<Client> getFriends() {
return friends;
}
/**
* #param friends the friends to set
*/
public void setFriends(Set<Client> friends) {
this.friends = friends;
}
/**
* #return the parent
*/
public Client getParent() {
return parent;
}
/**
* #param parent the parent to set
*/
public void setParent(Client parent) {
this.parent = parent;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Client [username=" + username + ", email=" + email + "]";
}
}
The problem is that after adding a new friend to a Client and searching for the same Client by Id, the friend list isn't updated correctly.
I tried your entity in an existing project I have setup, and it seems to work fine for me. I'm using play 2.1.1 with java 1.7, and Scala 2.10.0. There is this issue with enhancement that could be causing your issue.