Making SQL/JPQL query to select all topics that matches both keywords - sql

Challenge:
I want to create a query that selects Topics that match both the keyword ID´s "Java" and "sql", the Topic with ID = 1 matches both keywords "Java" and "Sql.
I have implemented two simple entities Topic and Keyword. They have a bidirectional ManyToMany relationship:
#Entity
#Table(name = "Topic")
public class Topic implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "topicID")
private Long id;
#Column(name = "topicTitle")
private String title = "";
#ManyToMany
#JoinTable(name = "Join_Topic_Keyword",
joinColumns = #JoinColumn(name = "Topic_ID"),
inverseJoinColumns = #JoinColumn(name = "Keyword_ID"))
private Set<Keyword> keywords;
}
#Entity
#Table(name = "Keyword")
public class Keyword implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "keywordID")
private String id;
#ManyToMany(mappedBy = "keywords")
private Set<Topic> topics;
}
Here is the structure table.
And This is the result from Join_Topic_Keyword

Related

How to make JPA JOIN query list giving only one item instead of all items by condition

I have some Entities looks like this. Very abstract:
#Entity
class Man {
#Id
String name;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "name", cascade = CascadeType.ALL)
List<Car> carList;
}
#IdClass(TypeId.class)
#Entity
class Car {
#Id
#NonNull
String name;
#Id
#NonNull
String class;
#ManyToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "class",
referencedColumnName = "class",
insertable = false,
updatable = false)
Engine engine;
}
#Entity
class Engine() {
#Id
#NonNull
String class;
String type;
Integer count;
}
class TypeId {
String name;
String class;
}
I need to construct #Query - select MAN with condition: if Engine types are equals, I need to take one Car with less Engine count. And return Man with only one Car if condition is met. Otherwise return Man with all cars.

JPA Query mapping

I want to use orderNumber in ProductRepository but I keep getting SQL error. I mapped both sides.
this is product entity.
#Entity
public class Product extends BaseEntity {
#Id
#GeneratedValue
#Column(name = "product_id")
private Long id;
#ManyToOne
#JoinColumn(name = "orderItem_id")
private OrderItem orderItem;
this is orderItem entity.
#Entity
public class OrderItem extends BaseEntity {
#Id
#GeneratedValue
#Column(name = "orderItem_id")
private Long id;
private String orderNumber
#OneToMany(mappedBy = "orderItem", cascade = CascadeType.ALL, orphanRemoval = true)
#Builder.Default
private List<Product> products = new ArrayList<Product>();
this is query in ProductRepository.
#Query(value = "SELECT * FROM OrderItem a, Product b WHERE a.orderItem_id = b.orderItem_id", nativeQuery = true)
Product findByOrderNumber(String orderNumber);
Alternatively, you can try query by a method as shown below, you don't need to use the #Query in this case.
ProductRepository
Product findByOrderItemOrderNumber(String orderNumber);
you can find more details here

How to implement bidirectional hibernate relationship correctly?

#Entity
#Table(name = "project")
public class Project {
#Id
#Column(name = "project_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#OneToOne
#JoinColumn(name = "idea_id", referencedColumnName = "idea_id")
#JsonIgnore
private Idea idea; .......}
And
#Entity
#Table(name = "idea")
public class Idea {
#Id
#Column(name = "idea_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Size(max = 240)
#NotNull
private String description;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "project_id", referencedColumnName = "project_id")
private Project project; ..........}
What is wrong with my hibernate relationships in these two classes? This is example of relationship that I want to implement.
And this is actual tables that I get with these relationships:
Idea table:
And Project table:
How to get rid of null values in idea_id column in project table?

#Query Spring Data JPA Update Not Working

Here is my User entity:
#Entity
#Table(name="users")
public class User implements IBaseEntity<User> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long userId;
#Column(unique = true)
#NotNull
private String username;
#Column(unique = true)
#NotNull
private String email;
#Column
#NotNull
private String password;
// #formatter:off
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "users_roles",
joinColumns = { #JoinColumn(name = "user_id") },
inverseJoinColumns = { #JoinColumn(name = "role_id") })
// #formatter:on
private List<Role> roles = new ArrayList<Role>();
#Column
#NotNull
private Boolean locked;
...
}
Here is my Role entity:
#Entity
#Table(name="roles")
public class Role implements IBaseEntity<Role> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long roleId;
#Column(unique = true)
#NotNull
private String name;
...
}
Here is my User service:
package org.quickloanconnect.service;
public interface IUsersService extends IBaseService<User>{
public void updateUserRolesById(List<Role> roles, Long userId);
...
}
Here is the UserServiceImpl :
#Service
#Transactional
public class UsersServiceImpl extends AbstractServiceImpl<User> implements
IUsersService {
...
#Override
#Transactional
public void updateUserRolesById(List<Role> roles, Long user_id) {
userDao.updateUserRolesById(roles, user_id);
}
...
}
And here is the dao:
public interface IUsersDao {
...
#Modifying
#Query("UPDATE User u SET u.roles = :roles WHERE u.userId = :userId")
public void updateUserRolesById(#Param("roles") List<Role> roles,
#Param("userId") Long userId);
...
}
When I run this update, I get the following: SqlExceptionHelper : No value specified for parameter 2 . What is causing this? When I update my user with a single role, I see that a List of size one is getting to the dao with the correct userId (both parameters present), but the update seems to fail at the dao level with the "SqlExceptionHelper : No value specified for parameter 2" error message.

JPA : Implicit find by composite primary key

Please I'm trying to find Quiz by Audit (using spring data jpa) and there must be an implicit search for the quizSubCategory which has a composite key, here are the classes :
Quiz entity:
#Entity
#Table(name = "quiz")
public class Quiz {
#EmbeddedId
private QuizCK id;
#Column
private String title;
#Column
private String status;
#Column
private String state;
#Column(name = "start_date")
private Date startDate;
#Column(name = "end_date")
private Date endDate;
#Column
private String reference;
#Column
private String results;
#Column(name = "is_default")
private boolean isDefault;
#ManyToOne
#JoinColumn(name = "id_audit")
private Audit audit;
#ManyToOne
#JoinColumns({
#JoinColumn(name = "id_quiz_sub_category", insertable = false, updatable = false),
#JoinColumn(name = "id_language", insertable = false, updatable = false)
})
private QuizSubCategory quizSubCategory;
#MapsId("idLanguage")
#ManyToOne
#JoinColumn(name="id_language", insertable = false, updatable = false)
private Language language;
public Quiz() {
}
// constructor & getters & setters
}
QuizSubCategory entity:
Entity
#Table(name = "quiz_sub_category")
public class QuizSubCategory implements Serializable {
#EmbeddedId
private QuizSubCategoryCK id;
private String libelle;
#ManyToOne
#JoinColumns({
#JoinColumn(name = "id_quiz_category", insertable = false, updatable = false),
#JoinColumn(name = "id_language", insertable = false, updatable = false)
})
private QuizCategory quizCategory;
#MapsId("idLanguage")
#ManyToOne
#JoinColumn(name="id_language", insertable = false, updatable = false)
private Language language;
public QuizSubCategory() {
super();
}
//constructor & getters & setters
}
QuizSubCategoryCK (primary key):
#Embeddable
public class QuizSubCategoryCK implements Serializable {
#Column(name = "id_quiz_sub_category", insertable = false, updatable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private int idQuizSubCategory;
#Column(name = "id_language", insertable = false, updatable = false)
private int idLanguage;
public QuizSubCategoryCK() {
}
public int getIdQuizSubCategory() {
return idQuizSubCategory;
}
public void setIdQuizSubCategory(int idQuizSubCategory) {
this.idQuizSubCategory = idQuizSubCategory;
}
public int getIdLanguage() {
return idLanguage;
}
public void setIdLanguage(int idLanguage) {
this.idLanguage = idLanguage;
}
}
QuizRepository :
public interface QuizRepository extends JpaRepository<Quiz,QuizCK> {
List<Quiz> findByAuditAndLanguage(Audit audit, Language language);
}
Controller:
#RequestMapping(value = "/quizzes/{auditId}", method = RequestMethod.GET)
public List<QuizBean> listQuizzes(#PathVariable int auditId){
AuditBean auditBean = auditService.getAudit(auditId);
LanguageBean languageBean = languageService.getLanguageById(1);
List<QuizBean> quizzes = quizService.findByAudit(AuditMapper.fromBean(auditBean),LanguageMapper.fromBean(languageBean));
return quizzes;
}
I'm getting the following error :
Unable to find jpa.entity.QuizSubCategory with id jpa.entity.QuizSubCategoryCK#79a59c48; nested exception is javax.persistence.EntityNotFoundException: Unable to find jpa.entity.QuizSubCategory with id jpa.entity.QuizSubCategoryCK#79a59c48
Any hints please ?!