Trouble with hibernate and json - java

So i have a user and a client.The user can have multiple clients.But json cannot return a value user.
So i did something like this :
#Column
private Integer fkIdUser ;
But i'm new to hibernate and i'm wondering if this is the right way of doing this. Or do i need to use a class with a many to one annotation but how would i do this with json ?
User class
public class User {
public static User globalUser;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_user")
private Integer id;
#Column(unique = true)
private String email;
Then the Client class
#Entity
#Table(name ="tbl_clients")
#Access(value = AccessType.FIELD)
public class Client {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_client")
private Integer id;
/* This works
#Column
private Integer fkIdUser ;
*/
// This does not
#ManyToOne
#JoinColumn(name = "fk_id_user")
private User user;
I'm using this function in the ClientController to store the client to the database
#RequestMapping(value = "/addclient",method = RequestMethod.POST)
public void addClient(#RequestBody Client client) {
clientDao.save(client);
}

You have to use the same name of the column in the #JoinColumn name. Since you are using fkIdUser as the variable and it works, I suppose this is your column name. Then your mapping should be like this:
#ManyToOne
#JoinColumn(name = "fkIdUser")
private User user;

Related

How do I properly update tables in a One to Many Hibernate relationship (by one request)?

I am using Postgresql via Hibernate, there are three tables: users, products, user_products. Here are their mappings
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(nullable = false)
#NotBlank
private String name;
#OneToMany(cascade = CascadeType.ALL)
private List<Products> product;
}
#Entity
public class Product{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(nullable = false)
#NotBlank
private String name;
#Column(nullable = false)
private Integer price;
}
i know that i can get user by id, then update its field "products" and than save user back. But is it possible to do all this stuff by one request via Hibernate (or using raw sql query)?
I would create a separate Entity UserProduct and save it.
Is there some reason this won't work?

How can I store an object (entity) in memory to get it later only in a working application with Hibernate?

How can I store an object (entity) in memory to get it later only in a working application with Hibernate?
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private long id;
#Column(name = "name")
private String name;
#Column(name = "password")
private String password;
//without save this to database but in memory
private boolean drunk;
}
How to get an object from memory with variable "drunk"?
I'm using now this to get object:
session.createQuery("SELECT u FROM User u WHERE u.name LIKE :name")
.setParameter("name", name)
.getResultList();
You can user #Transient annotation, It indicates that a field is not to be persisted in the database.
import javax.persistence.Transient;
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private long id;
#Column(name = "name")
private String name;
#Column(name = "password")
private String password;
//without save this to database but in memory
#Transient
private boolean drunk;
}
However you would need to define how this value would be set after you read it again from database later.

How can I convert this 3 JOIN query into a Spring Data JPA named query method?

I am not so into Spring Data JPA and I have the following problem trying to implement a named query (the query defined by the method name).
I have these 3 entity classes:
#Entity
#Table(name = "room_tipology")
public class RoomTipology implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "tipology_name")
private String name;
#Column(name = "tipology_description")
private String description;
#Column(name = "time_stamp")
private Date timeStamp;
#OneToMany(mappedBy = "roomTipology")
private List<Room> rooms;
#OneToOne(mappedBy = "roomTipology")
private RoomRate roomRate;
// GETTER AND SETTER METHODS
}
That represents a tipology of room and that contains this field
#OneToMany(mappedBy = "roomTipology")
private List<Room> rooms;
So it contains the list of room associated to a specific room tipology, so I have this Room entity class:
#Entity
#Table(name = "room")
public class Room implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#ManyToOne
#JoinColumn(name = "id_accomodation_fk", nullable = false)
private Accomodation accomodation;
#ManyToOne
#JoinColumn(name = "id_room_tipology_fk", nullable = false)
private RoomTipology roomTipology;
#Column(name = "room_number")
private String number;
#Column(name = "room_name")
private String name;
#Column(name = "room_description")
#Type(type="text")
private String description;
#Column(name = "max_people")
private Integer maxPeople;
#Column(name = "is_enabled")
private Boolean isEnabled;
// GETTER AND SETTER METHODS
}
Representing a room of an accomodation, it contains this annoted field:
#ManyToOne
#JoinColumn(name = "id_accomodation_fk", nullable = false)
private Accomodation accomodation;
And finally the Accomodation entity class:
#Entity
#Table(name = "accomodation")
public class Accomodation implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#OneToMany(mappedBy = "accomodation")
private List<Room> rooms;
#Column(name = "accomodation_name")
private String name;
#Column(name = "description")
#Type(type="text")
private String description;
// GETTER AND SETTER METHODS
}
Ok, so now I have this Spring Data JPA repository class for RoomTipology:
#Repository
#Transactional(propagation = Propagation.MANDATORY)
public interface RoomTipologyDAO extends JpaRepository<RoomTipology, Long> {
}
Here I want to define a named query method that return to me the list of all the RoomTipology object related to a specific accomodation, I have done it using SQL and it works fine:
SELECT *
FROM room_tipology as rt
JOIN room r
ON rt.id = r.id_room_tipology_fk
JOIN accomodation a
ON r.id_accomodation_fk = a.id
WHERE a.id = 7
But now I want to translate it in a named query method (or at least using HQL)
How can I do it?
Please Try:
#Repository
#Transactional(propagation = Propagation.MANDATORY)
public interface RoomTipologyDAO extends JpaRepository<RoomTipology, Long> {
List<RoomTipology> findByRooms_Accomodation(Accomodation accomodation);
}
The query builder mechanism built into Spring Data repository infrastructure is useful for building constraining queries over entities of the repository. The mechanism strips the prefixes find…By, read…By, query…By, count…By, and get…By from the method and starts parsing the rest of it
At query creation time you already make sure that the parsed property is a property of the managed domain class. However, you can also define constraints by traversing nested properties.
Doc:Here

JPA Criteria seems to ignore join on condition

I've a User and Contact entities in my app and I need to every user can add some private comment about every contact and that comment must be available only for that user. So I create new entity - PrivateInfo. Here's the code.
User class:
#Entity
#Table(name = "users")
#XmlAccessorType(XmlAccessType.FIELD)
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String login;
// other fields
}
Contact class:
#Entity
#Table(name = "contacts")
#XmlAccessorType(XmlAccessType.FIELD)
public class Contact implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#OneToMany(fetch = LAZY, cascade = ALL, mappedBy = "contact")
private Set<PrivateInfo> privateInfo;
// etc.
}
PrivateInfo class:
#Entity
#Table(name = "private_info")
#XmlAccessorType(XmlAccessType.FIELD)
public class PrivateInfo implements Serializable {
#EmbeddedId
private PrivateInfoKey pk;
#Column(name = "additional_info")
private String additionalInfo;
#ManyToOne(fetch = FetchType.EAGER)
#MapsId("contactId")
private Contact contact;
}
#Embeddable
public class PrivateInfoKey implements Serializable {
#Column(name = "contact_id")
private Long contactId;
#Column(name = "user_id")
private Long userId;
}
I'm using Spring Data repositories with JpaSpecificationExecutor for querying so here's my attempt to write specification for getting all contacts with private info for specific user.
public static Specification<Contact> withPrivateInfo(final long userId) {
return new Specification<Contact>() {
#Override
public Predicate toPredicate(Root<Contact> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Join<Contact, PrivateInfo> joinPrivateInfo = root.join(Contact_.privateInfo, JoinType.LEFT);
joinPrivateInfo.on(cb.equal(
joinPrivateInfo.get(PrivateInfo_.pk).get(PrivateInfoKey_.userId), userId
));
return cb.conjunction(); // translates in sql like '... where 1 = 1'
}
};
}
However, when I call
contactRepository.findAll(withPrivateInfo(1));
I'm receiving contacts and each of them contains in privateInfo field all users information about this contact (not only for user with id = 1, as expected). Seems like join on condition ignored.
Any suggestions how to achieve my goal? Maybe with another entities structure. Is this possible with JPA/Criteria?

Retrieve logged user object and save it as a foreign key

While saving some data from the form I also need to add FK to the Record table. FK is User.Id.
I know how to save data from the input field on the form, but how can I set FK (int value) to this:
#ManyToOne
#JoinColumn(name = "id")
#Cascade({CascadeType.ALL})
private User user;
Is there some way to retrieve object which relates to logged user and make something like this: record.setUser(user)?
I've googled it but I didn't manage to find how to achive this.
This is my entity class.
#Entity
public class Record implements java.io.Serializable{
#Id
#GeneratedValue
private int recordId;
private String recordName;
private String recordComment;
private Date recordDate;
private Integer price;
#ManyToOne
#JoinColumn(name = "userId", insertable = true, updatable = false)
#Cascade({CascadeType.ALL})
private User user;
......
}
#Entity
#Table(name = "system_user")
public class User implements java.io.Serializable{
#Id
#GeneratedValue
private int userId;
#NotEmpty
#Email
private String email;
#Size(min=2, max=30)
private String name;
private String enabled;
#NotEmpty
private String password;
private String confirmPassword;
#Enumerated(EnumType.STRING)
#Column(name = "user_role")
private Role role;
#OneToMany(fetch = FetchType.EAGER,mappedBy = "user", orphanRemoval=true)
#Cascade({CascadeType.ALL})
private List<Record> records;
public void addToRecord(Record record) {
record.setUser(this);
this.records.add(record);
}
....
}
This is how I save data to DB:
#RequestMapping(value = "/protected/add", method = RequestMethod.POST)
public String addCost (#ModelAttribute("record") Record record,HttpSession session){
User user = userManager.getUserObject(userManager.getUserId(session.getAttribute("currentUser").toString()));
user.addToRecord(record);
recordService.addRecord(record);
return "redirect:/protected/purse";
}
DAO:
public void addRecord(Record record) {
sessionFactory.getCurrentSession().save(record);
}
UPDATE: problem was partially solved, code above works fine for me.
You also need to create User object and set the user object in a Record object using the below code
record.setUser(userObj);
and user foreign key will be automatically saved in database.

Categories