Spring : create object with id from another table - java

I created objects User and Message, and now I want, that message's id will be associated with the user id. How can I do it with annotations or with something else?
Table User
Table Messge
Message class
#Entity
public class Message {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String text;
private String tag;
}
User class
#Entity
#Table(name = "usr")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
private String password;
private boolean active;
#ElementCollection(targetClass = Role.class , fetch = FetchType.LAZY)
#CollectionTable(name = "user_role" , joinColumns = #JoinColumn(name = "user_id"))
#Enumerated(EnumType.STRING)
private Set<Role> roles;
}

you can try this:
Message class:
#Entity
public class Message {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String text;
private String tag;
#ManyToOne
#JoinColumn(name = "user_id")
private User userId;
}
user class:
#Entity
#Table(name = "usr")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
private String password;
private boolean active;
#ElementCollection(targetClass = Role.class , fetch = FetchType.LAZY)
#CollectionTable(name = "user_role" , joinColumns = #JoinColumn(name = "user_id"))
#Enumerated(EnumType.STRING)
private Set<Role> roles;
#OneToMany(mappedBy = "user")
#JsonBackReference
private set<Message> messages;
}

Related

How to map a String to an application object in Mapstruct

Let's say I have this UserRole class.
It contains the roles of each user.
#Entity
#Table(name="user_roles")
public class UserRole implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column
private long userRoleId;
#ManyToOne
#JoinColumn(name = "user_id", foreignKey = #ForeignKey(name = "users_fk"), nullable=false)
private User user;
#ManyToOne
#JoinColumn(name = "role_id", foreignKey = #ForeignKey(name = "roles_fk"), nullable=false)
private Role role;
...
}
Now I want to have a DTO class with just userName and role that will map to the original class.
public class UserRoleRequestDTO {
private String userName;
private String role;
...
}
How do I create a mapper for that?
#Mapper
public interface UserRoleMapper {
#Mapping(//** What goes here? **//)
UserRole UserRoleRequestDTOtoUserRole(UserRoleRequestDTO userRoleRequestDTO);
}

Is there a way to return user rating of a one book for that user?

I am working on a project, trying to create an AudioBook website. I am stuck on this part and i cant find answers on the internet.
The problem is when i get user, and list of favorite books, each book has list of user rating, from all of the users. And also there is a list of UserRatings that contains all of ratings from that user. I dont want neither.
Basically, is there a way to make it so when i do a search for list of books, every book object contains UserRating(One user rating) from a specific User that is logged in?
#Entity
#Table(name = "user_rating")
public class user_rating {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
private Integer Id;
#Column
private String rating;
#ManyToOne
#JoinColumn(name = "user_id")
private users user;
#ManyToOne
#JoinColumn(name = "book_id")
private books book;
#Entity
#Table(name = "users")
public class users {
#Id
#Column
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column
private String name;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#Column(name = "date_of_creation")
private java.sql.Date dateOfCreation;
#Column
private String password;
#JsonManagedReference
#ManyToMany
#JoinTable(
name = "favourites",
joinColumns = #JoinColumn(name = "user_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "book_id", referencedColumnName = "id")
)
private Set<books> favourites = new HashSet<>();
#OneToMany(mappedBy ="user")
private List<user_rating> UserRating = new ArrayList<>();
#Entity
#Table(name = "books")
public class books {
#Id
#Column
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column
private String name;
#Column
private String description;
#Column(name = "date_of_creation")
private java.sql.Date date_of_creation;
#Column
private String text_file;
#JsonBackReference
#ManyToMany(mappedBy = "favourites")
private Set<users> users = new HashSet<>();
#JsonManagedReference
#ManyToMany()
#JoinTable(
name = "book_tags",
joinColumns = #JoinColumn(name = "book_id", referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "tag_id", referencedColumnName = "id")
)
private List<tags> tags = new ArrayList<>();
#OneToOne
#PrimaryKeyJoinColumn
private audio_file audioFile;
#OneToMany(mappedBy = "book")
private List<user_rating> UserRatings = new ArrayList<>();

JPA one2many relation, how to keep the ids

I have 3 entity classes: User, Product and Fridge. The Fridge is something between User and Product. I mean that in the Fridge I store the ID of the Product, the id of the User and some quantity. And I need to see the IDs that are(stored) used for relation.
User Entity Class:
#Entity
#Table(name = "`user`")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
#NotNull
#Column(name = "username")
private String username;
#NotNull
#Column(name = "password")
private String password;
#OneToMany(mappedBy="user")
#JsonManagedReference(value = "user-fridge")
private List<Fridge> fridge;
}
Product Entity Class :
#Entity
#Table(name = "product")
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
#Column(name = "name")
private String name;
#Column(name = "measurementUnit")
private Enum measurementUnit;
#Column(name = "calories")
private int calories;
#OneToMany(mappedBy="product")
#JsonManagedReference(value = "ingredients-products")
private List<Ingredients> ingredients;
#OneToMany(mappedBy="product")
#JsonManagedReference(value = "fridge-product")
private List<Fridge> fridge;
}
Fridge Entity Class :
#Entity(name = "Fridge")
#Table(name = "fridge")
public class Fridge{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
#ManyToOne
#JoinColumn(name="user_id")
#JsonBackReference(value = "user-fridge")
private User user;
#ManyToOne
#JoinColumn(name="product_id")
#JsonBackReference(value = "fridge-product")
private Product product;
#Column(name = "quantity")
private int quantity;
#Transient
private DateFormat dform = new SimpleDateFormat("dd/MM/yy");
#Transient
private Date intermediar = new Date();
#Column(name = "added_at")
private String added_at = dform.format(intermediar);
}
What I get is something like this :
"fridge": [
{
"id": "79baae3e-8189-4ebb-8a40-2116a77693b8",
"quantity": 25,
"added_at": "25/08/21"
}
But I need the id's of the product and user as well.
How should I structure my model to get that?

Insert data to multiple tables in spring jpa

I have two tables, user and transaction. Where one user can have many transactions. So, everytime I create new user, they automatically make new transaction and the transaction type is SEND MONEY. But I don't understand how to write it in Spring JPA. Please take a look on my code and help me.
User.java
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private long id;
#Column(name = "name")
private String name;
#Column(name = "email")
private String email;
#Column(name = "password")
private String password;
#Column(name = "money")
private int money;
//Getter Setter Constructor
}
Transaction.java
#Entity
#Table(name = "transaction")
public class Transaction {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id_trans")
private long id_trans;
#Column(name = "id_user")
private long id_user;
#Column(name = "transaction_date")
private Timestamp transaction_date;
#Column(name = "type") //Default set as "SEND MONEY"
private String type;
#Column(name = "trans_money") //From money in User.class
private int trans_money;
//Getter Setter Constructor
}
I know I should do something in my UserDAO.java, but I still don't know how to send data from body and split(?) it into two object (user and transaction, so I can persist it in UserDAO).
First of all, you have to write the relationship between User and Transaction.
#Entity
#Table(name = "user")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private long id;
#Column(name = "name")
private String name;
#Column(name = "email")
private String email;
#Column(name = "password")
private String password;
#Column(name = "money")
private int money;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private Set<Transaction> transactions = new HashSet<>();
//Getter Setter Constructor
}
#Entity
#Table(name = "transaction")
public class Transaction {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id_trans")
private long id_trans;
#Column(name = "id_user")
private long id_user;
#Column(name = "transaction_date")
private Timestamp transaction_date;
#Column(name = "type") //Default set as "SEND MONEY"
private String type;
#Column(name = "trans_money") //From money in User.class
private int trans_money;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(referencedColumnName = "id")
private User user;
//Getter Setter Constructor
}
Then you have to create the JPA repository interface for the User
#Repository
public interface UserRepo extends CrudRepository <User, Long> {
}
Then in a service, you can do the following
#Service
public class UserService {
private UserRepo userRepo;
#Autowired
MealService(UserRepo userRepo){
this.userRepo = userRepo;
}
public void CreateNewUser(){
User user = new User();
// set its values
Transaction transaction = new Transaction();
transaction.setType("SEND MONEY");
// set other values
user.getTransactions().add(transaction);
userRepo.save(user);
}
}
Looking at the #Entity classes mentioned it seems to me that there exists an #ManyToOne association between Transaction and User which is not captured in the entity relationship modeling/mapping.
Please consider modeling that in your Transaction entity as follows,
#Entity
#Table(name = "transaction")
public class Transaction {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id_trans")
private long id_trans;
#ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.MERGE}, fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
private User user;
#Column(name = "transaction_date")
private Timestamp transaction_date;
#Column(name = "type") //Default set as "SEND MONEY"
private String type;
#Column(name = "trans_money") //From money in User.class
private int trans_money;
//Getter Setter Constructor
}
Once you do that you can create a JPA repository class for Transaction and User and simply use the save method to do what you want in a transaction after constructing your instances. More on transactions in Spring Data JPA here
public interface TransactionRepository extends JpaRepository<Transaction, Long> {
}

More than one row with the given identifier was found: 1, for class: mz.co.zonal.models.Product

I'm trying to get All Product into database, it seems well but always i have this error of integrity.
More than one row with the given identifier was found: 1, for class: mz.co.zonal.models.Product; nested exception is org.hibernate.HibernateException: More than one row with the given identifier was found: 1, for class: mz.co.zonal.models.Product
My Classes is
public class Product implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
private String title;
#NotNull
private String description;
#NotNull
private double price;
#ManyToOne(fetch = FetchType.EAGER)
private Category category;
private boolean sold;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
private Currency currency;
#ManyToOne
#CreatedBy
private User user;
#Nullable
#OneToMany(mappedBy = "product",
cascade = CascadeType.ALL, orphanRemoval = true)
private List<Images> images;
private Date createdDate = new Date();
#OneToMany(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "product")
private List<View> view;
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name="type_id")
private Type type;
private Long viewCount;
#ManyToOne(fetch=FetchType.EAGER, cascade={CascadeType.ALL})
#JoinColumn(name="brand_id")
private Brand brand;
#Nullable
#OneToMany(mappedBy = "product",
cascade = CascadeType.ALL, orphanRemoval = true)
private List<ProductLikes> productLikes;
#Nullable
#Column
#ElementCollection(targetClass=byte.class)
private List<byte[]> imagesByte;}
#Entity
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Category implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
private String name;
#NotNull
private String imagePath;
#OneToMany(cascade = CascadeType.ALL,
mappedBy = "category")
#JsonIgnore
private List<Product> product;
#Nullable
private byte[] categoryImage;}
#Entity
public class Currency implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
private String code;
#NotNull
private String currency;
#NotNull
private String region_country;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
#OneToMany(mappedBy = "currency", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JsonIgnore
private List<Product> products;
}
#Entity
public class ProductLikes {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Boolean isLike;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
#JsonIgnore
private User user;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "product_id", nullable = false)
#JsonIgnore
private Product product;}
#Entity
public class Images implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String imagePath;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "product_id")
private Product product;
}
#Entity
public class Type implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
private String name;
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "type")
#JsonIgnore
private Product product;
}
#Entity
public class User implements UserDetails, Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotEmpty
private String fullName;
#NotEmpty
#Email
#Column(unique = true)
private String email;
#NotNull
#Column(unique = true)
private int phoneNumber;
#NotEmpty
#Size(min = 5)
private String password;
private Date createAt = new Date();
#Nullable
private String picPath;
#Nullable
private String token;
#ManyToMany
#JoinTable(name = "user_roles", joinColumns = {#JoinColumn(
name = "user_id")},
inverseJoinColumns = {#JoinColumn(name = "role_id")})
private List<Role> roles;
#OneToOne(fetch = FetchType.EAGER,
cascade = CascadeType.ALL,
mappedBy = "user")
#JsonIgnore
private Product product;
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "user")
private View view;
}
#Entity
public class View implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "user_id", nullable = false)
#JsonIgnore
private User user;
#OneToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "product_id", nullable = false)
#JsonIgnore
private Product product;
}
#Entity
public class Brand implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
private String name;
#OneToMany(fetch=FetchType.EAGER, mappedBy="brand", cascade={CascadeType.ALL})
#JsonIgnore
private List<Product> products;}
I'm not sure if this is the only cause of problems, but you have mapped the relation between Product and Type as 1:1 but the rows in the database both reference the same type_id 1.

Categories

Resources