ive been working on this for a while and can't seem to figure it out except that at some point it was working as was intended. I have two objects, a User which can be associatted with multiple addresses. Saving a new user and address together works just fine, but when i try to add a new address to an existing User i get an error about duplicate primary keys for User table. I guess it has something to do with the configuration in hibernate trying both unidirectional and bidirectional.
Below are any relevant files. Thanks of your help!
User.java
#Entity
#Table(name = "users")
public class Users implements Serializable {
private static final long serialVersionUID = -5699491123012997265L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int idusers;
#NotBlank(groups = { PersistenceValidationGroup.class, FormValidationGroup.class })
#Size(min = 5, max = 15, groups = { PersistenceValidationGroup.class, FormValidationGroup.class })
#Pattern(regexp = "^\\w{5,}$", groups = { PersistenceValidationGroup.class, FormValidationGroup.class })
private String username;
#NotBlank(groups = { PersistenceValidationGroup.class, FormValidationGroup.class })
#Pattern(regexp = "^\\S+$", groups = { PersistenceValidationGroup.class, FormValidationGroup.class })
#Size(min = 8, max = 15, groups = { FormValidationGroup.class })
private String password;
private boolean enabled = false;
private String authority;
#Size(max = 25, groups = { PersistenceValidationGroup.class, FormValidationGroup.class })
private String name;
#Size(min = 10, max = 10, groups = { PersistenceValidationGroup.class, FormValidationGroup.class })
private String phoneNo;
#OneToMany(fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
#JoinColumn(name = "idaddresses")
private Set<Addresses> addresses;
// CONSTRUCTORS
public Users() {
}
public Users(String username, String password, boolean enabled,
String authority, String name, String phoneNo,
Set<Addresses> addresses) {
this.username = username;
this.password = password;
this.enabled = enabled;
this.authority = authority;
this.name = name;
this.phoneNo = phoneNo;
this.addresses = addresses;
}
// GETTERS AND SETTERS
public int getIdUsers() {
return idusers;
}
public void setIdusers(int idusers) {
this.idusers = idusers;
}
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 boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getIdusers() {
return idusers;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public Set<Addresses> getAddresses() {
return addresses;
}
public void setAddresses(Set<Addresses> addresses) {
this.addresses = addresses;
}
public void addAddress(Addresses addresses) {
if (this.addresses == null) {
this.addresses = new HashSet<Addresses>();
}
addresses.setUsers(this);
this.addresses.add(addresses);
}
}
Addresses.java
#Entity
#Table(name = "addresses")
public class Addresses implements Serializable {
private static final long serialVersionUID = -1239830513656245466L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int idaddresses;
#NotBlank
#Size(min = 5, max = 45)
private String street1;
#NotBlank
#Size(min = 5, max = 45)
private String street2;
#Size(min = 0, max = 200)
private String special;
private String apt;
private String city;
private String state;
#ManyToOne
#JoinColumn(name = "idusers")
private Users users;
// CONSTRUCTORS
public Addresses() {
}
public Addresses(String street1, String street2, String special,
String apt, String city, String state, Users users) {
this.street1 = street1;
this.street2 = street2;
this.special = special;
this.apt = apt;
this.city = city;
this.state = state;
this.users = users;
}
// GETTERS AND SETTERS
public int getIdaddresses() {
return idaddresses;
}
public void setIdaddresses(int idaddresses) {
this.idaddresses = idaddresses;
}
public String getStreet1() {
return street1;
}
public void setStreet1(String street1) {
this.street1 = street1;
}
public String getStreet2() {
return street2;
}
public void setStreet2(String street2) {
this.street2 = street2;
}
public String getSpecial() {
return special;
}
public void setSpecial(String special) {
this.special = special;
}
public String getApt() {
return apt;
}
public void setApt(String apt) {
this.apt = apt;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Users getUsers() {
return users;
}
public void setUsers(Users users) {
this.users = users;
}
}
Part of flow that calls method
<view-state id="newAddress" model="address">
<transition on="addNewAddress" to="customerReady" />
<on-exit>
<evaluate expression="address.street1 = requestParameters.street1"></evaluate>
<evaluate expression="address.street2 = requestParameters.street2"></evaluate>
<evaluate expression="address.apt = requestParameters.apt"></evaluate>
<evaluate expression="address.city = requestParameters.city"></evaluate>
<evaluate expression="address.special = requestParameters.special"></evaluate>
<evaluate expression="address.city = requestParameters.city"></evaluate>
<evaluate expression="address.state = 'NY'"></evaluate>
<evaluate expression="user.addAddress(address)"></evaluate>
<evaluate expression="usersService.update(user)"></evaluate>
</on-exit>
</view-state>
userService.update(user) sends you to dao
public void update(Users users) {
session().saveOrUpdate(users);
}
Related
I have entity Account, Role, AccountRole.
#Entity
public class Account {
#Id
private String loingId;
private String username;
private String password;
private String email;
private boolean enable;
#OneToMany(mappedBy = "account", orphanRemoval = true)
private List<AccountRole> accountRoles = new ArrayList<>();
public String getLoingId() {
return loingId;
}
public void setLoingId(String loingId) {
this.loingId = loingId;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public List<AccountRole> getAccountRoles() {
return accountRoles;
}
public void setAccountRoles(List<AccountRole> accountRoles) {
this.accountRoles = accountRoles;
}
public void addAccountRoles(AccountRole accountRoles) {
if (this.accountRoles == null){
this.accountRoles = new ArrayList<>();
}
this.accountRoles.add(accountRoles);
accountRoles.setAccount(this);
}
public void removeAccountRoles(){
this.accountRoles = null;
}
}
#Entity
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String description;
private boolean enable;
#OneToMany(mappedBy = "role")
private List<AccountRole> accountRoles = new ArrayList<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public List<AccountRole> getAccountRoles() {
return accountRoles;
}
public void setAccountRoles(List<AccountRole> accountRoles) {
this.accountRoles = accountRoles;
}
}
#Entity
public class AccountRole implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#ManyToOne
#JoinColumn(name = "account_id")
private Account account;
#ManyToOne
#JoinColumn(name = "role_id")
private Role role;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
}
To create account with role is OK.
There is a problem in update.
I want to delete the existing Role and only add the changed Role when the Role of the Account is changed. However, existing data is not deleted from the AccoutRole table.
How can I solve the problem?
springBootVersion = '1.5.3.RELEASE'
java 1.8
gradle dependencies
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
testCompile('org.springframework.boot:spring-boot-starter-test')
runtime ('org.mariadb.jdbc:mariadb-java-client')
}
A couple of ideas:
Thought 1: Try using cascade
Yes, JPA 2.0 should handle this with orphanRemoval = true, but let's just see if that works. I think that it is not because you aren't creating an orphan here. The mapping is still "valid" from a relational perspective.
#OneToMany(mappedBy = "account", cascade = CascadeType.ALL) // or CascadeType.REMOVE
private List<AccountRole> accountRoles = new ArrayList<>();
Thought 2: Try setting the account roles to an empty hashmap instead first:
account.setAccountRoles(new HashMap<AccountRole>());
account.getAccountRoles().add(accountRole);;
I'm using servlets with JPA+Hibernate). I don't understand the error, unless I've tried other solutions suggested in this forum. In fact, I don't want to store the UserAccount class as an entity; but I just want to declare it in the Utilisateur class (the Ids of the Utilisateur class are declared in the useraccount class).
My code :
#Entity
#Table(name = "utilisateur")
public class Utilisateur implements Serializable {
#Id
private UserAccount userAccount;
private Civility civility;
private Address address;
private Contact contact;
#Column(name = "sessions")
private List<String> sessions;
#Column(name = "particularRules")
private boolean particularRules;
public Utilisateur(UserAccount pAccount, Civility pCivility,
Address pAddress, Contact pContact, List<String>
pSessions,
boolean particularRules) {
this.userAccount = pAccount;
this.civility = pCivility;
this.address = pAddress;
this.contact = pContact;
this.sessions = pSessions;
this.particularRules = particularRules;
}
public Civility getCivility() {
return civility;
}
public void setCivility(Civility civility) {
this.civility = civility;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Contact getContact() {
return contact;
}
public void setContact(Contact contact) {
this.contact = contact;
}
public boolean isParticularRules() {
return particularRules;
}
public void setParticularRules(boolean particularRules) {
this.particularRules = particularRules;
}
public UserAccount getUserAccount() {
return userAccount;
}
public void setUserAccount(UserAccount userAccount) {
this.userAccount = userAccount;
}
public List<String> getSessions() {
return sessions;
}
public void setSessions(List<String> sessions) {
this.sessions = sessions;
}
}
#Embeddable
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class UserAccount implements Serializable {
public UserAccount() {
}
public UserAccount(String pId, String pEmail, String pwsd, Date pCreaDate, Date pLastModDate) {
this.identifier = pId;
this.email = pEmail;
this.password = pwsd;
this.creationDate = pCreaDate;
this.lastModificationDate = pLastModDate;
}
#OneToOne(mappedBy = "userAccount", cascade = CascadeType.ALL,
fetch = FetchType.EAGER, orphanRemoval = true, targetEntity =
Utilisateur.class)
private Utilisateur user;
#Column(name = "creationDate")
#Temporal(javax.persistence.TemporalType.DATE)
private Date creationDate;
#Column(name = "lastModificationDate")
#Temporal(javax.persistence.TemporalType.DATE)
private Date lastModificationDate;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "identifier", nullable = false)
private String identifier;
#Column(name = "email")
private String email;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "password", nullable = false)
private String password;
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
this.identifier = identifier;
}
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 Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Date getLastModificationDate() {
return lastModificationDate;
}
public void setLastModificationDate(Date lastModificationDate) {
this.lastModificationDate = lastModificationDate;
}
public Utilisateur getUser() {
return user;
}
public void setUser(Utilisateur user) {
this.user = user;
}
}
You must use an Embedded Primary Key.
See the answer to this question here in Stackoverflow How to create and handle composite primary key in JPA.
Best regards!
It may occur when Embedded Primary Key contains #EmbeddedId. Sub-composite key should be annotated with #Embedded instead.
i have this error nested exception is org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): app.Spring.domain.UserDetails.
I now have this user table and in profile i want to edit this UserDetails.
i was trying with GeneratedValue but this doing random id that not associate with user_id also checked generator but this method also dont work.There is so many options so i am lost now.Can someone show some method to mapp this two entities?
User
#Entity
#Table(name = "USERS")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "user_id")
private Long user_id;
#NotBlank
#Size(min = 5, max = 20)
private String username;
#NotBlank
#Size(min = 8, max = 20)
private String password;
private String email;
private String name;
private String surname;
#OneToOne(cascade = CascadeType.ALL)
#PrimaryKeyJoinColumn
private UserDetails userDetail;
public User() {
}
public User(Long user_id, String username, String email, String name,
String surname, UserDetails userDetail, String password) {
super();
this.user_id = user_id;
this.username = username;
this.email = email;
this.name = name;
this.surname = surname;
this.userDetail = userDetail;
this.password = password;
}
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 getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Long getUser_id() {
return user_id;
}
public final void setUser_id(Long user_id) {
this.user_id = user_id;
}
public void setId(Long user_id) {
this.user_id = user_id;
}
#Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
User_Details
#Entity
#Table(name = "user_address")
public class UserDetails {
public UserDetails() {
super();
// TODO Auto-generated constructor stub
}
#Id
#Column(name = "user_id")
private Long id;
private String adres1;
private String adres2;
private String city;
private String postcode;
#OneToOne
#PrimaryKeyJoinColumn
private User user;
public UserDetails(Long id, String adres1, String adres2, String city,
String postcode, User user) {
super();
this.id = id;
this.adres1 = adres1;
this.adres2 = adres2;
this.city = city;
this.postcode = postcode;
this.user = user;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getAdres1() {
return adres1;
}
public void setAdres1(String adres1) {
this.adres1 = adres1;
}
public String getAdres2() {
return adres2;
}
public void setAdres2(String adres2) {
this.adres2 = adres2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public void setId(Long id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
LOGIC
#RequestMapping(value = "/userDetails", method = RequestMethod.GET)
public String showForm(Model model,
#RequestParam(value = "id", defaultValue = "-1") Long id,
HttpSession session) {
app.Spring.domain.UserDetails va = (id > 0) ? reg.getAdress(id)
: new UserDetails();
model.addAttribute("detal", va);
return "userDetails";
}
#RequestMapping(value = "/userDetails", method = RequestMethod.POST)
public String submit(Model model, #ModelAttribute("detal") UserDetails va,
BindingResult result) {
validator.validate(va, result);
if (result.hasErrors()) {
return "userDetails";
}
reg.saveOrUpdateUserDetails(va);
return "profile";
}
I don't know how to do this with annotations but you might try to manually assign the (hopefully then already present) id fetched from user in the UserDetails entity in the #PrePresist annotated method.
User
#Entity
#Table(name = "USERS")
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Column(name = "user_id")
private Long user_id;
#NotBlank
#Size(min = 5, max = 20)
private String username;
#NotBlank
#Size(min = 8, max = 20)
private String password;
private String email;
private String name;
private String surname;
#OneToOne(mappedBy = "user")
private UserDetails userDetail;
User_detail
#Entity
#Table(name = "user_address")
public class UserDetails {
public UserDetails() {
super();
// TODO Auto-generated constructor stub
}
#Id
private Long id;
private String adres1;
private String adres2;
private String city;
private String postcode;
#OneToOne
#JoinColumn(name = "user_id")
private User user;
What is wrong with this code?
When I post a tweet, the page stays blank, when I check the database, the tweets are there but the userId key is null, it's not a naming issue I named it user_id but is always null, I don't know what the problem is, this should work, no?
#Entity
public class Tweets {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "tweet", length = 500)
private String tweet;
#ManyToOne
#JoinColumn(name = "userId")
private User user;
public Tweets() {
}
public Tweets(String tweet, User user) {
this.setTweet(tweet);
this.setUser(user);
}
public long getId() {
return id;
}
/*
public void setId(long id) {
this.id = id;
}
*/
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getTweet() {
return tweet;
}
public void setTweet(String tweet) {
this.tweet = tweet;
}
}
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;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "user", cascade=CascadeType.ALL)
private List<Tweets> tweets;
public List<Tweets> getTweets() {
return tweets;
}
public void setTweets(List<Tweets> tweets) {
this.tweets = tweets;
}
public void setUsername(String username) {
this.username = username;
}
#Column(nullable = false)
private String username;
/*
* //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;
}
public String getUsername() {
return username;
}
}
I have a doubt and consequently I don't know how proceed correctly. I have three different tables like in figure below. I'm using JPA. Here is the code generated automatically by Netbeans that shows the entities. My question is What should I persist into the database? If I put only user, I will have automatically persisted also phone numbers and client? i'm pretty confused
Here it is a code
UserCredential user = new UserCredential();
user.setUsername(username);
user.setPassword(utilBean.hashPassword(password));
user.setEmail(email);
Client client = new Client();
client.setUserCredential(user);
client.setName(name);
client.setSurname(surname);
client.setAddress(address);
client.setCity(city);
client.setZipCode(zipCode);
client.setCountry(country);
client.setFidelityPoints(0);
ClientPhoneNumbers phoneNumber = new ClientPhoneNumbers();
phoneNumber.setUsername(username);
if(homeNumber != null || !(homeNumber.equals("")))
{
phoneNumber.setCountryCodeHome(areaCodeHomeNumber);
phoneNumber.setHome(homeNumber);
}
phoneNumber.setCountryCodeMobile(areaCodeMobileNumber);
phoneNumber.setMobile(mobileNumber);
client.setClientPhoneNumbers(phoneNumber);
em.persist(user);
USER CREDENTIAL
#Entity
#Table(name = "user_credential")
#NamedQueries(
{
#NamedQuery(name = "UserCredential.findAll", query = "SELECT u FROM UserCredential u")
})
public class UserCredential implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 16)
#Column(name = "username")
private String username;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "email")
private String email;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "password")
private String password;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "groupname")
private String groupname;
#Column(name = "create_time")
#Temporal(TemporalType.TIMESTAMP)
private Date createTime;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "userCredential")
private Client client;
public UserCredential()
{
}
public UserCredential(String username)
{
this.username = username;
}
public UserCredential(String username, String email, String password, String groupname)
{
this.username = username;
this.email = email;
this.password = password;
this.groupname = groupname;
}
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 String getGroupname()
{
return groupname;
}
public void setGroupname(String groupname)
{
this.groupname = groupname;
}
public Date getCreateTime()
{
return createTime;
}
public void setCreateTime(Date createTime)
{
this.createTime = createTime;
}
public Client getClient()
{
return client;
}
public void setClient(Client client)
{
this.client = client;
}
#Override
public int hashCode()
{
int hash = 0;
hash += (username != null ? username.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object)
{
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof UserCredential))
{
return false;
}
UserCredential other = (UserCredential) object;
if ((this.username == null && other.username != null) || (this.username != null && !this.username.equals(other.username)))
{
return false;
}
return true;
}
#Override
public String toString()
{
return "it.volaconoi.entity.UserCredential[ username=" + username + " ]";
}
}
CLIENT
#Entity
#Table(name = "client")
#NamedQueries(
{
#NamedQuery(name = "Client.findAll", query = "SELECT c FROM Client c")
})
public class Client implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 16)
#Column(name = "username")
private String username;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "name")
private String name;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "surname")
private String surname;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "address")
private String address;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "city")
private String city;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
#Column(name = "zip_code")
private String zipCode;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "country")
private String country;
#Basic(optional = false)
#NotNull
#Column(name = "fidelity_points")
private int fidelityPoints;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "client")
private ClientPhoneNumbers clientPhoneNumbers;
#JoinColumn(name = "username", referencedColumnName = "username", insertable = false, updatable = false)
#OneToOne(optional = false)
private UserCredential userCredential;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "username")
private Collection<Reservation> reservationCollection;
public Client()
{
}
public Client(String username)
{
this.username = username;
}
public Client(String username, String name, String surname, String address, String city, String zipCode, String country, int fidelityPoints)
{
this.username = username;
this.name = name;
this.surname = surname;
this.address = address;
this.city = city;
this.zipCode = zipCode;
this.country = country;
this.fidelityPoints = fidelityPoints;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getSurname()
{
return surname;
}
public void setSurname(String surname)
{
this.surname = surname;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getZipCode()
{
return zipCode;
}
public void setZipCode(String zipCode)
{
this.zipCode = zipCode;
}
public String getCountry()
{
return country;
}
public void setCountry(String country)
{
this.country = country;
}
public int getFidelityPoints()
{
return fidelityPoints;
}
public void setFidelityPoints(int fidelityPoints)
{
this.fidelityPoints = fidelityPoints;
}
public ClientPhoneNumbers getClientPhoneNumbers()
{
return clientPhoneNumbers;
}
public void setClientPhoneNumbers(ClientPhoneNumbers clientPhoneNumbers)
{
this.clientPhoneNumbers = clientPhoneNumbers;
}
public UserCredential getUserCredential()
{
return userCredential;
}
public void setUserCredential(UserCredential userCredential)
{
this.userCredential = userCredential;
}
public Collection<Reservation> getReservationCollection()
{
return reservationCollection;
}
public void setReservationCollection(Collection<Reservation> reservationCollection)
{
this.reservationCollection = reservationCollection;
}
#Override
public int hashCode()
{
int hash = 0;
hash += (username != null ? username.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object)
{
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Client))
{
return false;
}
Client other = (Client) object;
if ((this.username == null && other.username != null) || (this.username != null && !this.username.equals(other.username)))
{
return false;
}
return true;
}
#Override
public String toString()
{
return "it.volaconoi.entity.Client[ username=" + username + " ]";
}
}
** PHONE NUMBERS **
#Entity
#Table(name = "client_phone_numbers")
#NamedQueries(
{
#NamedQuery(name = "ClientPhoneNumbers.findAll", query = "SELECT c FROM ClientPhoneNumbers c")
})
public class ClientPhoneNumbers implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 16)
#Column(name = "username")
private String username;
#Size(max = 8)
#Column(name = "country_code_home")
private String countryCodeHome;
#Size(max = 45)
#Column(name = "home")
private String home;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 8)
#Column(name = "country_code_mobile")
private String countryCodeMobile;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "mobile")
private String mobile;
#JoinColumn(name = "username", referencedColumnName = "username", insertable = false, updatable = false)
#OneToOne(optional = false)
private Client client;
public ClientPhoneNumbers()
{
}
public ClientPhoneNumbers(String username)
{
this.username = username;
}
public ClientPhoneNumbers(String username, String countryCodeMobile, String mobile)
{
this.username = username;
this.countryCodeMobile = countryCodeMobile;
this.mobile = mobile;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getCountryCodeHome()
{
return countryCodeHome;
}
public void setCountryCodeHome(String countryCodeHome)
{
this.countryCodeHome = countryCodeHome;
}
public String getHome()
{
return home;
}
public void setHome(String home)
{
this.home = home;
}
public String getCountryCodeMobile()
{
return countryCodeMobile;
}
public void setCountryCodeMobile(String countryCodeMobile)
{
this.countryCodeMobile = countryCodeMobile;
}
public String getMobile()
{
return mobile;
}
public void setMobile(String mobile)
{
this.mobile = mobile;
}
public Client getClient()
{
return client;
}
public void setClient(Client client)
{
this.client = client;
}
#Override
public int hashCode()
{
int hash = 0;
hash += (username != null ? username.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object)
{
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ClientPhoneNumbers))
{
return false;
}
ClientPhoneNumbers other = (ClientPhoneNumbers) object;
if ((this.username == null && other.username != null) || (this.username != null && !this.username.equals(other.username)))
{
return false;
}
return true;
}
#Override
public String toString()
{
return "it.volaconoi.entity.ClientPhoneNumbers[ username=" + username + " ]";
}
}
If you want to persist client as well, you have to call user.setClient(client) before calling persist.