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.
Related
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
I want to make association to some many-to-many relation entity
#Entity
#Table(name = "users")
#Data
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
private String userId;
private String name;
#OneToMany(mappedBy = "user")
private List<UserGroups> userGroups;
#Table(name = "groups")
#Data
public class Group {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "group_id")
private String groupId;
private String category;
private String name;
private String description;
#OneToMany(mappedBy = "group")
private List<UserGroups> userGroups;
public void addUser(User user){
UserGroup newUserGroup = new UserGroup();
newUserGroup.setName(user.getName())
userGroups.add(newUserGroup);
user.getUserGroups().add(newUserGroup)
}
#Entity
#Data
#Table(name = "user_groups")
public class UserGroups {
#EmbeddedId
UserGroupsCompositeKey id;
#ManyToOne
#MapsId("userId")
#JoinColumn(name = "user_id")
private Users user;
#ManyToOne
#MapsId("featureId")
#JoinColumn(name = "group_id")
private Group group;
private Date created;
I trying to add POST method to service where I should get group_id from endpoint url and assosiate user_id in request body. My Service method looks like this.
#Override
public ResponseEntity<String> createUsersGroup(String groupId,
String userId) {
Optional<Group> group = groupRepository.findById(groupId).get();
Optional<User> user = userRepository.findById(userId).get();
group.addUser(user);
return ResponseEntity.ok(userId);
};
}
Is there some more proper way to do this or when I will add more users in request body I will have to pull out every user from the database and add it like that ?
For example, I have the User class, with looks like the next:
#Entity
#Table(name = "users")
public class User{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#NotBlank
#Size(max = 40)
#Column(name = "name")
private String name;
#NotBlank
#Size(max = 15)
#Column(name = "username")
private String username;
#NaturalId
#NotBlank
#Size(max = 40)
#Email
#Column(name = "email")
private String email;
#NotBlank
#Size(max = 100)
#Column(name = "password")
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<>();
//Constructor
//Getters and Setters
And I have the Client class:
#Entity
#Table(name = "cliente")
public class Cliente {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "empresa")
private String empresa;
#Column(name = "telefono")
private Integer telefono;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(unique = true)
private Licencia licencia;
#OneToMany(cascade = {
CascadeType.PERSIST,
CascadeType.REMOVE
} ,fetch = FetchType.EAGER)
#JoinTable(name = "user_cliente",
joinColumns = #JoinColumn(name = "cliente_id"),
inverseJoinColumns = #JoinColumn(name = "user_id"))
private Set<User> users = new HashSet<>();
public Cliente(String empresa, Integer telefono) {
this.empresa = empresa;
this.telefono = telefono;
}
//Constructor
//Getters and Setters
Now, what I want to do is the Client class to extends the User class, so I can add a Client with name, username, email, etc. But I want two separate tables in MySQL, one for the users and its attributes, and other for clients only with the information of client, like the telephone or company. The problem is when I extends the User class in Client class, the MySQL databases updates and create the fields of telephone, company, etc. in the User table. How can I avoid this?
Use #MappedSuperclass:
#MappedSuperclass
public class BaseEntity {
// here you can add common fields for your entities
}
and then extend from it:
#Entity
public class User extends BaseEntity {
// user specific fields goes here
}
and Client:
#Entity
#Table(name = "cliente")
public class Cliente extends BaseEntity {
// client specific fields here
}
For more info read How to inherit properties from a base class entity using #MappedSuperclass with JPA and Hibernate
I want to create a many to many relation in my application but it doesen't work.
My first entity:
#Entity
#Table(name = "Person")
public class Person implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Version
private Long version;
private String firstName;
private String lastName;
private String location;
private String email;
private String status;
private String role;
private LocalDateTime createdOn;
private LocalDateTime modifiedOn;
#ManyToMany(mappedBy = "persons")
private Set<Team> teams = new HashSet<Team>();
My second entity:
#Entity
#Table(name = "Team")
public class Team {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Version
private Long version;
private String name;
private String description;
private String city;
private Integer headcount;
private LocalDateTime createdOn;
private LocalDateTime modifiedOn;
#ManyToMany(cascade = CascadeType.MERGE)
#JoinTable(name = "persons_teams",
joinColumns = #JoinColumn(name = "teamId"),
inverseJoinColumns = #JoinColumn(name = "personId"))
private Set<Person> people = new HashSet<>();
I don't know what is wrong but the program doesn't compile.
Please help.
In Person class you have indicated the name of field to be mapped in Team by using name "persons" but the actual field name in Team class is "people".
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!