How to query One-to-Squillions - java

I have 2 classes.
User class
#Entity("user")
public class User {
#Id
ObjectId id;
String companyName;
String email;
private byte[] image;
}
Ticket class: ownerId reference to 'user' table
#Entity("ticket")
public class Ticket {
#Id
private ObjectId id;
private ObjectId ownerId;
}
I want to fetch users that is ticket's owner. What is the best way to do that with Morphia?

#Entity("ticket")
public class Ticket {
#Id
private ObjectId id;
#Reference
private User user;
}
So whenever you fetch a ticket, you can directly access the user.

Related

Using Spring Data JPA method name, how to find by foreign keys?

I have entities like below:
public class UserName {
#Id
private Long id;
private String name;
#OneToMany(mappedBy = "userName")
private User;
}
public class UserAge {
#Id
private Long id;
private int age;
#OneToMany(mappedBy = "userAge")
private User;
}
public class User {
#Id
private Long id;
#ManyToOne
private UserName userName;
#ManyToOne
private UserAge userAge;
}
When I search users whose name is the one with UserName.id = 100,
how can I do that?
I found an almost same question here, however it didn't work like below
public interface UserRepository extends JpaRepository<User, Long>{
Long countByUserNameId(Long id);
}

Spring JPA mapping - first steps

I have class User:
#Entity
public class User {
#Id
#GeneratedValue
private Integer id;
private String name;
private String password;
#ManyToMany
#JoinTable
private List<Role> roles;
}
Class Owner inherits from User
#Entity
public class Owner extends User {
private String pesel;
private String adress;
#OneToMany(cascade={CascadeType.PERSIST, CascadeType.REMOVE})
private List<Pet> pets;
}
and Owner had Pet
public class Pet {
#Id
#GeneratedValue
private Integer id;
private String name;
private String weight;
#ManyToOne
private Owner owner;
}
Why when starting the application gets the error:
org.springframework.data.mapping.PropertyReferenceException: No
property user found for type Pet!
--EDIT
First I have version, which was as follows:
now I try to share User instance to a doctor and the owner of the animal
The problem is that I do not know whether I am doing the mapping , and therefore wanted to ask whether it must look like
--edit2
I've simplified the scheme just a bit to better illustrate what happens
--edit3
Currently my Object's was presented:
#Entity
public class Pet {
#Id
#GeneratedValue
private Integer id;
private String name;
private String weight;
}
User
#Entity
public class User {
#Id
#GeneratedValue
private Integer id;
private String name;
private String password;
#ManyToMany
#JoinTable(name="user_roles")
private List<Role> roles;
}
PetOwner
#Entity
public class PetOwner extends User {
private String pesel;
private String adress;
#OneToMany(mappedBy="petOwner")
private List<Pet> pets;
}
I replace
#ManyToOne
private PetOwner petOwner;
for
#ManyToOne
private Owner petOwner;
and it works. Do you have a PetOwner class?
Also provide the log error to get more information about it

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.

how to use a generated value for a field in a dependent object?

I am using JPA to store my objects in the database. I have a User class that has as a field (One to One relationship) a Password class. When a new user registers I want the generated Id for the User class to also be the id field for the Password class. Any ideas on how to go about this? Here is the relevant code...
#Entity
#Table(name="users")
public class User {
#Id
#GeneratedValue(strategy=SEQUENCE,generator="user_id_seq")
#Column(name="user_id")
private int id;
#Column(name="username")
private String username;
#OneToOne(cascade=CascadeType.PERSIST)
#JoinColumn(name="user_id")
private Password password;
}
#Entity
#Table(name="passwords")
public class Password {
#Id
//#GeneratedValue ???
#Column(name="user_id")
int userId;
#Column(name="password")
String password;
}
Give Password a direct reference to its parent User and mark that field as your id:
#Entity
#Table(name="passwords")
public class Password {
#Id
User user;
// ...
}
Alternatively, if you still want the primitive userId field, use #MapsId:
#Entity
#Table(name="passwords")
public class Password {
#Id
int userId;
#MapsId
#OneToOne
#JoinColumn(name = "user_id")
User user;
// ...
}

OneToOne with the same PrimaryKey and ForeignKey

Database
*user_account*
id (PK)
email
password
*user_detail*
id(PK)(FK)
name
city
Entities
#Table(name="user_detail")
public class UserDetail implementsSerializable{
#Id private Integer id;
...
#OneToOne
#JoinColumn(name="id")
private UserAccount userAccount;
}
#Table(name="user_account")
public class UserAccount implementsSerializable{
#Id private Integer id;
#OneToOne(mappedBy="userAccount")
private UserDetail userDetails;
}
Error
Exception Description: Multiple writable mappings exist for the field [user_detail.ID]. Only one may be defined as writable, all others must be specified read-only.
If the ID in UserAccount is both a primary key and a foreign key, then you should declare it as a single field and map it appropriately. Like this:
#Entity
public class UserAccount implements Serializable {
#Id
#OneToOne(mappedBy="userAccount")
private UserDetail userDetails;
}
Or else using #MapsId.
However, i suspect that what you really want is a single class spread over two tables:
#Entity
#Table(name = "user_account")
#SecondaryTable(name = "user_detail")
public class User implements Serializable {
#Id
private int id;
private String email;
private String password;
#Column(table = "user_detail")
private String name;
#Column(table = "user_detail")
private String city;
}
You cannot have both #Id private Integer id; and #JoinColumn(name="id"), you must remove one of them: I doubt that you really need a primary key in the details, so just remove the #Id line from there.

Categories