Identifier Generation Exception - java

I have some problems with identifier generation. I use MySQL database. So, I have two entities:
#Entity
#Table(name = "users", catalog = "test1")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id", unique=true, nullable=false, updatable=false)
private Long id;
private String username;
private String password;
private boolean enabled;
#JsonBackReference
private Set<UserRole> userRole = new HashSet<UserRole>(0);
#OneToOne(cascade={CascadeType.ALL}, fetch = FetchType.LAZY, targetEntity = Utilisateur.class)
#JoinColumn(name="userUtilisateur")
#JsonManagedReference
private Utilisateur userUtilisateur;
/*.. getters and setters..*/ }
and
#Entity
#Table(name="utilisateur")
public class Utilisateur {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "firstName")
private String firstName;
#Column(name = "lastName")
private String lastName;
private String fullName;
#Column(name = "age")
private int age;
#OneToMany(mappedBy="utilisateur", targetEntity = Ticket.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JsonBackReference
private Set<Ticket> tickets = new HashSet<Ticket>(0);
#OneToMany(mappedBy="utilisateur", targetEntity=UserAssignProject.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JsonBackReference
private Set<UserAssignProject> userAssignProjects = new HashSet<UserAssignProject>(0);
#OneToMany(mappedBy="utilisateur", targetEntity=Message.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JsonBackReference
private Set<Message> messages = new HashSet<Message>(0);
/*.. getters and setters..*/ }
I have this method in UserDaoImpl:
public void save(User user) {
Utilisateur utilisateur = new Utilisateur();
user.setId(user.getId());
user.setUsername(user.getUsername());
user.setPassword(user.getPassword());
user.setEnabled(true);
user.setUserUtilisateur(utilisateur);
getCurrentSession().save(user);
}
Results:
Exception here
I've tried to use sequence, GenerationType.AUTO..., but it's not working.
Any solutions?
Thanks for your attention!

Related

How do I retrieve parent object with child object while having OneToMany bidriectional relationship in spring boot?

I am new to Spring boot. please help me with the below issue:
I am getting only child object data while retrieving using join query..
Below is my child entity class:
#Entity
#Table(name = "tenant_user_configuration")
public class TenantUserConfiguration {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "config_key")
private String configKey;
#Column(name = "config_value")
private String configValue;
private String system;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="tenant_user_id",referencedColumnName = "tenant_user_id")
#JsonBackReference
private TenantUser tenantUser;
This is my parent entity class:
#Entity
#Table(name = "tenant_user")
public class TenantUser {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "tenant_user_id")
private int tenantUserId;
#OneToOne
#JoinColumn(name = "tenant_id",referencedColumnName = "tenant_id")
private Tenant tenant;
#Column(name = "user_name")
private String userName;
#Column(name = "password")
private String password;
#Column(name = "enabled")
private boolean enabled;
#OneToMany(mappedBy = "tenantUser",fetch = FetchType.EAGER)
#JsonManagedReference
private Set<TenantUserConfiguration> tenantUserConfiguration = new HashSet<>();

How can I implement this Spring Data JPA query by method name that retrieve a specific object based on two properties?

I am working on a Spring Boot project using Spring Data JPA trying to adopt the "query by method name" style in order to define my queries into repositories.
I am finding some difficulties trying to implement a select query retrieving the list of objects based on two different "where condition". I will try to explain what I have to do.
First of all this is my main entity class named Wallet:
#Entity
#Table(name = "wallet")
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Wallet implements Serializable {
private static final long serialVersionUID = 6956974379644960088L;
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name = "address")
private String address;
#Column(name = "notes")
private String notes;
#ManyToOne
#EqualsAndHashCode.Exclude // Needed by Lombock in "Many To One" relathionship to avoid error
#JoinColumn(name = "fk_user_id", referencedColumnName = "id")
#JsonBackReference(value = "user-wallets")
private User user;
#ManyToOne
#EqualsAndHashCode.Exclude // Needed by Lombock in "Many To One" relathionship to avoid error
#JoinColumn(name = "fk_coin_id", referencedColumnName = "id")
private Coin coin;
#ManyToOne
#JoinColumn(name = "type", referencedColumnName = "id")
private WalletType walletType;
public Wallet(String address, String notes, User user, Coin coin, WalletType walletType) {
super();
this.address = address;
this.notes = notes;
this.user = user;
this.coin = coin;
this.walletType = walletType;
}
}
As you can see a wallet is directly binded to a specific User object and to a specific Coin object.
For completeness this is the code of my User entity class:
#Entity
#Table(name = "portal_user")
#Getter
#Setter
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class User implements Serializable {
private static final long serialVersionUID = 5062673109048808267L;
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
#Column(name = "first_name")
#NotNull(message = "{NotNull.User.firstName.Validation}")
private String firstName;
#Column(name = "middle_name")
private String middleName;
#Column(name = "surname")
#NotNull(message = "{NotNull.User.surname.Validation}")
private String surname;
#Column(name = "sex")
#NotNull(message = "{NotNull.User.sex.Validation}")
private char sex;
#Column(name = "birthdate")
#NotNull(message = "{NotNull.User.birthdate.Validation}")
private Date birthdate;
#Column(name = "tax_code")
#NotNull(message = "{NotNull.User.taxCode.Validation}")
private String taxCode;
#Column(name = "e_mail")
#NotNull(message = "{NotNull.User.email.Validation}")
private String email;
#Column(name = "pswd")
#NotNull(message = "{NotNull.User.pswd.Validation}")
private String pswd;
#Column(name = "contact_number")
#NotNull(message = "{NotNull.User.contactNumber.Validation}")
private String contactNumber;
#Temporal(TemporalType.DATE)
#Column(name = "created_at")
private Date createdAt;
#Column(name = "is_active")
private boolean is_active;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
#JsonManagedReference(value = "address")
private Set<Address> addressesList = new HashSet<>();
#ManyToMany(cascade = { CascadeType.MERGE })
#JoinTable(
name = "portal_user_user_type",
joinColumns = { #JoinColumn(name = "portal_user_id_fk") },
inverseJoinColumns = { #JoinColumn(name = "user_type_id_fk") }
)
private Set<UserType> userTypes;
#ManyToOne(fetch = FetchType.LAZY)
#JsonProperty("subagent")
private User parent;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
#JsonManagedReference(value = "user-wallets")
private Set<Wallet> wallets = new HashSet<>();
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(String firstName, String middleName, String surname, char sex, Date birthdate, String taxCode,
String email, String pswd, String contactNumber, Date createdAt, boolean is_active) {
super();
this.firstName = firstName;
this.middleName = middleName;
this.surname = surname;
this.sex = sex;
this.birthdate = birthdate;
this.taxCode = taxCode;
this.email = email;
this.pswd = pswd;
this.contactNumber = contactNumber;
this.createdAt = createdAt;
this.is_active = is_active;
}
}
and this is the code of my Coin entity class:
#Entity
#Table(name = "coin")
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Coin implements Serializable {
private static final long serialVersionUID = 6956974379644960088L;
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name = "name")
#NotNull(message = "{NotNull.Coin.name.Validation}")
private String name;
#Column(name = "description")
private String description;
#Column(name = "code", unique = true)
#NotNull(message = "{NotNull.Coin.code.Validation}")
private String code;
#Type(type="org.hibernate.type.BinaryType")
#Column(name = "logo")
private byte[] logo;
}
Then I have this WalletRepository interface:
public interface WalletRepository extends JpaRepository<Wallet, Integer> {
}
Here I need to define a query by name method that retrieve a specific wallet of a specific User (I think that I can query by the id field of the User) and based and related to a specific Coin (I think that I can query by the id fied of the Coin).
How can I implement a behavior like this?
The following should work:
public interface WalletRepository extends JpaRepository<Wallet, Integer> {
List<Wallet> findByUserIdAndCoinId();
}
You can read more about this at:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repository-query-keywords

mappedBy reference an unknown target entity property role based

1 user ==> many roles
1- role ==> many components
for this I have configured like
userDao.java
#Entity
#Table(name = "User_info")
public class UserDao {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
#Column(name="username")
private String username;
#Column(name="password")
#JsonIgnore
private String password;
#ManyToMany(cascade=CascadeType.MERGE,fetch = FetchType.EAGER)
#JoinTable(
name="user_role",
joinColumns={#JoinColumn(name="USER_ID", referencedColumnName="userId")},
inverseJoinColumns={#JoinColumn(name="ROLE_ID", referencedColumnName="roleId")})
private List<Role> roles;
Role.java
#Entity
#Table(name = "roles")
public class Role {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
private Integer roleId;
#Column(nullable = false, unique = true)
#NotEmpty
private String roleName;
#ManyToMany(mappedBy = "roles")
private List < UserDao > users;
#ManyToMany(cascade=CascadeType.MERGE,fetch = FetchType.EAGER)
#JoinTable(
name="role_component",
joinColumns={#JoinColumn(name="ROLE_ID", referencedColumnName="roleId")},
inverseJoinColumns={#JoinColumn(name="COMP_ID", referencedColumnName="compId")})
private List<Component> components;
component.java
#Entity
#Table(name = "component")
public class Component {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer compId;
#Column(nullable = false, unique = true)
#NotEmpty
private String compName;
#ManyToMany(mappedBy = "component")
private List < Role > roles;
I am getting the following error, Please suggest the mistake
Caused by: org.hibernate.AnnotationException: mappedBy reference an
unknown target entity property:
net.springboot.helloworldapp.bean.Role.component in
net.springboot.helloworldapp.bean.Component.roles at
org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:785)
There is a typo. component should be components.
#ManyToMany(mappedBy = "components") // <- should be components
private List < Role > roles;

could not resolve property: userId.username

I have following entity classes:
#MappedSuperclass
public class AbstractEntity implements Serializable, Comparable<AbstractEntity> {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
protected Integer id;
#Override
public int compareTo(AbstractEntity o) {
return this.toString().compareTo(o.toString());
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
#Entity
#Table(name = "ticket")
#NamedQueries({
#NamedQuery(name = "Ticket.findAll", query = "SELECT t FROM Ticket t")})
public class Ticket extends AbstractEntity {
#Column(name = "title")
private String title;
#Column(name = "description")
private String description;
#Enumerated(EnumType.STRING)
#Column(name = "status")
private TicketStatus status;
#Enumerated(EnumType.STRING)
#Column(name = "priority")
private TicketPriority priority;
#Column(name = "categories")
private String categories;
#Column(name = "views")
private Integer views;
#Column(name = "date_time_created")
#Temporal(TemporalType.TIMESTAMP)
private Date dateTimeCreated;
#Column(name = "date_time_modified")
#Temporal(TemporalType.TIMESTAMP)
private Date dateTimeModified;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "ticketId")
private List<TicketFollower> ticketFollowerList;
#JoinColumn(name = "project_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private Project projectId;
#JoinColumn(name = "ticket_attachment_id", referencedColumnName = "id")
#ManyToOne
private TicketAttachment ticketAttachmentId;
#JoinColumn(name = "user_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private User userId;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "ticketId")
private List<TicketComment> ticketCommentList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "ticketId")
private List<TicketAttachment> ticketAttachmentList;
#Inject
public Ticket() {
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
...
#Override
public String toString() {
return getTitle();
}
}
#Entity
#Table(name = "user")
#NamedQueries({
#NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")})
public class User extends AbstractEntity {
#Enumerated(EnumType.STRING)
#Column(name = "role")
private Role role;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#Column(name = "avatar_path")
private String avatarPath;
#Column(name = "date_time_registered")
#Temporal(TemporalType.TIMESTAMP)
private Date dateTimeRegistered;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<TicketFollower> ticketFollowerList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<Ticket> ticketList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<TicketComment> ticketCommentList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<ProjectFollower> projectFollowerList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<TicketAttachment> ticketAttachmentList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userId")
private List<Project> projectList;
#Inject
public User() {}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
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 getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
I get this exception from creating a hibernate Criteria. In my TicketDao class I have a method which search ticket by username, and when I invoke code below
Criteria criteria = session.createCriteria(Ticket.class);
criteria.add(Restrictions.eq("userId.username", username));
it throws exception:
could not resolve property: userId.username of: com.entities.Ticket
However, when I write criteria like:
criteria.add(Restrictions.eq("userId.id", userId));
it does not show any exception and returns me result. Any idea why my syntax for criteria.add(Restrictions.eq("userId.username", username)); and other properties like firstname, last name is wrong ?
Criteria does not work like EL or Java methods or attributes, you cannot refer to inner objects with a dot ..
You have to create a restriction in Ticket, right? What does Ticket has? An User. Then... you have to create a new User, set the username to this User and then set the created User to Ticket's criteria:
Criteria criteria = session.createCriteria(Ticket.class);
User user = new User();
user.setUsername(username);
criteria.add(Restrictions.eq("user", user));

Why Hibernate ManyToOne is not persisted correctly?

I have two entities User and Wish :
#Entity
#Table(name = "T_USER")
public class User implements Serializable {
#Column(length = 50)
private String lastname;
#Column(length = 50)
private String firstname;
#OneToMany(mappedBy = "user",cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Wish> wishes = new HashSet<Wish>();
// getters and setters
}
#Entity
#Table(name = "T_WISH")
public class Wish implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "title")
private String title;
#Column(name = "description")
private String description;
#ManyToOne
private User user;
// getters and setters
}
When i save the user, recruiter_id is null why. I've tried :
Wish wish = wishRepository.save(wish);
user.getWishes.add(wish);
User userSaved = userRepository.save(user);
Why the recruiter_id is not set.
Your user class does not have #Id anottated field.

Categories