HOW JOIN two tables JPQL - spring-boot

How create a join pageable USING JPQL in Class Movie with MovieLanguage?
The Class Movie as a relationship 1 to 1 with MovieLanguage.
Movie:
Entity
#Table(name = "tb_movie")
public class Movie {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private Double score;
private Integer count;
private String image;
public Movie() {}
public Movie(Long id, String title, Double score, Integer count, String image) {
this.id = id;
this.title = title;
this.score = score;
this.count = count;
this.image = image;
}
#OneToOne(cascade = CascadeType.ALL, mappedBy = "movie")
#JsonManagedReference
MovieLanguage movieLanguage;
/* getter and setter */
}
MovieLanguage:
#Entity
#Table(name = "tb_movie_language")
public class MovieLanguage {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String titleBrazil;
private String titleSpanish;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "movie_id")
#JsonBackReference
private Movie movie;
public MovieLanguage(){}
/* getter and setter */
}
Here is a JPQL example in MovieJoinRepository, but not working:
MovieJoinRepository:
public interface MovieJoinRepository extends JpaRepository<Movie, Long> {
#Query("SELECT obj FROM Movie obj INNER JOIN obj.movie_language mm WHERE obj.id = mm.id ")
Page<String> findAllPaged(Pageable pageable);
}
Thank you for you help!

Related

Can I get the list of objects in relation #OneToMany?

I've got 2 classes: Device and Category. 1 Device can have 1 assigned category, but 1 category can have assigned many different devices.
#Entity
#Data
#Table(name = "devices")
public class Device implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
#Column(name="amount_of_items")
private Integer amountOfItems;
private BigDecimal price;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "category_id")
private Category category;
public Device(String name, String description, Integer amountOfItems, BigDecimal price, Category category){
this.name = name;
this.description = description;
this.amountOfItems = amountOfItems;
this.price = price;
this.category = category;
}
public Device() {}
}
#Entity
#Data
#Table(name = "categories")
public class Category implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
#OneToMany(mappedBy = "category", fetch = FetchType.EAGER)
private List<Device> devices = new ArrayList<>();
public Category(String name, String description){
this.name = name;
this.description = description;
}
public Category() { }
}
Can I get the actual list of devices for one Category? The below code returns me a null list of devices:
Category category = new Category("Urzadzenia AGD", "tylko dla klientow premium");
categoryRepository.save(category);
Device device = new Device("pralka", "samoobslugowa", 50, new BigDecimal("220"),
category);
deviceRepository.save(device);
System.out.println(category.getDevies()) ---> returns NULL
Can I do it by calling a getter like above?
save method already return value after save in Database you can use this
Category category = new Category("Urzadzenia AGD", "tylko dla klientow premium");
category= categoryRepository.save(category);
Device device = new Device("pralka", "samoobslugowa", 50, new BigDecimal("220"),
category);
deviceRepository.save(device);
System.out.println(category.getDevies())
and you must be make setter and getter method in your class
after this you have problem stackover flow exciption becouse the all device called category and categore call Devices
you can used #JsonIgnore annotation
Like this :
#OneToMany(mappedBy = "category", fetch = FetchType.EAGER)
#JsonIgnore
private List<Device> devices = new ArrayList<>();

Spring JPA projection with sublist

I have question about creating native query with custom response (spring projection) with nested „custom“ sublist i.e. i am trying to generate JSON output with nested sublists.
Child entity is:
#Entity
public class Child {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#NotNull
#Column(nullable = false)
private String firstName;
#NotNull
#Column(nullable = false)
private String secondName;
#Enumerated(EnumType.STRING)
private Gender gender;
private Date dateOfBirth;
private String phone;
#ManyToOne
#JoinColumn(name="child_id")
private List<Parent> parents = new ArrayList<Parent>();
//...
}
Parent entity is, for example:
#Entity
public class Parent {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#NotNull
#Column(nullable = false)
private String firstName;
#NotNull
#Column(nullable = false)
private String secondName;
private Date dateOfRegistration;
#OneToMany(fetch = FetchType.LAZY)
private List<Child> child = new ArrayList<Child>();
//...
}
Projection interface:
public interface ChildProjectionInterface {
public int getParentId();
public Date getFirstName();
public List<ChildResponse> getChildData();
interface ChildResponse {
public int getChildID();
public String getFirstName();
}
}
Query (but, obviously, doesn't working):
#Query(value = "SELECT p.id AS parentId, p.firstName AS firstName, c.id AS childData.childId, c.firstName AS childData.firstName FROM parent p LEFT JOIN child c ON p.child_id = c.child_id AND p.secondName = :secondName", nativeQuery = true)
List<ChildProjectionInterface> getListWithSubList(#Param(value ="secondName") String secondName);
I was reading and researching and trying..but nothing works (I saw https://medium.com/swlh/spring-data-jpa-projection-support-for-native-queries-a13cd88ec166, saw "for json auto" clause but not for spring jpa, etc.)
Did you try jpa fetch operator?
#Query("select p from parent p left join fetch p.child c where p.secondName = :secondName")

JPA Specification filtering nested object

I am trying to fetch nested object property but getting illegalArgument exception.
AuditTestingPlanSpecification name = new AuditTestingPlanSpecification(new SearchCriteria("auditPlanId.auditPlanEntity", ":",dates));
Page<AuditTestingPlanMaster> a = auditTestingPlanMasterRepository.findAll(name, ten);
Please find below code,
public class AuditTestingPlanSpecification implements Specification<AuditTestingPlanMaster> {
private SearchCriteria criteria;
public AuditTestingPlanSpecification(SearchCriteria searchCriteria) {
this.criteria = searchCriteria;
}
#Override
public Predicate toPredicate(Root<AuditTestingPlanMaster> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
if (root.get(criteria.getKey()).getJavaType() == String.class) {
return builder.like(root.<String>get(criteria.getKey()), "%" + criteria.getValue().get(0).toString() + "%");
} else {
return builder.equal(root.get(criteria.getKey()), criteria.getValue().get(0).toString());
}
return null;
}
}
Class SearchCriteria.java
public class SearchCriteria {
public SearchCriteria(String key, String operation, List<Object> value) {
super();
this.key = key;
this.operation = operation;
this.value = value;
}
private String key;
private String operation;
private List<Object> value;
// getters & setters
}
Class AuditTestingPlanMaster.java
#Entity
#Table(name = "audit_testing_plan_master")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class AuditTestingPlanMaster implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#Column(name = "risk_area_id")
private Long riskAreaId;
#Column(name = "expected_revert_date")
private Instant expectedRevertDate;
#Column(name = "created_date")
private Instant createdDate;
#Column(name = "last_modified_date")
private Instant lastModifiedDate;
#JoinColumn(name = "audit_plan_id", referencedColumnName = "id")
private AuditPlanMaster auditPlanId;
//getters & setters
}
Class AuditPlanMaster.java
#Entity
#Table(name = "audit_plan_master")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class AuditPlanMaster implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#Column(name = "remarks", length = 255)
private String remarks;
#Column(name = "audit_plan_entity", length = 50)
private String auditPlanEntity;
#Column(name = "start_date")
private Instant startDate;
#Column(name = "end_date")
private Instant endDate;
//getters & setters
}
I want to fetch all the AuditTestingPlanMaster objects whose AuditPlanMaster.auditPlanEntity string is matching with provided filter value.
Thank you for your time and help in advance.
I had the same problem, here is a snippet of how I handled it. My problem was when accessing id field from inner usuario object, in my case, id would be like your auditPlanEntity, and usuario would be like auditplanMaster:
public static Specification<UsuarioErrorEquipo> usuarioContains(String codigoUsuario) {
return (root, query, builder) -> {
Path<Usuario> u = root.get("usuario");
return builder.equal(u.get("id"), codigoUsuario);
};
}
I believe, that in your case it should be something like:
Path<AuditPlanMaster> u = root.get("auditPlanId");
return builder.equal(u.get("auditPlanEntity"), "the value you want to compare");

JPA - Join another entity by EmbeddedId with 2 columns

Basically. I have a ProductEntity, like this:
#Entity
#Table(name = "product", schema = "shop")
public class ShopProductEntity {
#EmbeddedId
private ProductEntityId id;
#Column(name = "product_name")
private String name;
#Column(name = "product_category_id")
private int categoryId;
#Column(name = "product_language_id")
private int languageId;
// TODO: Get category by categoryId and languageId.
private CategoryEntity category;
I have another CategoryIdentity:
#Entity
#Table(name = "category", schema = "shop")
public class CategoryEntity {
#EmbeddedId
private CategoryEntityId id;
#Column(name = "category_name")
private String name;
#Column(name = "category_url")
private String url;
It has an EmbeddedId like this:
#Embeddable
public class CategoryEntityId implements Serializable {
#Column(name = "category_id", nullable = false)
private int categoryId;
#Column(name = "language_id", nullable = false)
private int languageId;
public int getCategoryId() {
return categoryId;
}
public int getLanguageId() {
return languageId;
}
Now, every product has a category. Categories are unique by their id and language. The shop connects to a category by both the categoryId and languageId columns. How do I add the CategoryEntity to my ProductEntity so I can use the category's url value for my product?
I tried adding this to ShopProductEntity:
#ManyToOne
#JoinColumns({
#JoinColumn(name="categoryId", referencedColumnName="categoryId"),
#JoinColumn(name="languageId", referencedColumnName="languageId"),
})
private CategoryEntity category;

JPA repository null pointer exception for many to one mapping with composite primary key

Post class
one to many mapping
Composite primary key using id
I am getting null pointer exception when I make get request for getting comments
#Entity
#Table(name = "posts")
public class Post {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
#Size(max = 100)
#Column(unique = true)
private String title;
#NotNull
#Size(max = 250)
private String description;
#NotNull
#Lob
private String content;
#NotNull
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "posted_at")
private Date postedAt = new Date();
#NotNull
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "last_updated_at")
private Date lastUpdatedAt = new Date();
#OneToMany(cascade = CascadeType.ALL,
fetch = FetchType.LAZY,
mappedBy = "post")
private Set<Comment> comments = new HashSet<>();
public Post() {
}
public Post(String title, String description, String content) {
this.title = title;
this.description = description;
this.content = content;
}
//getters and setters
}
Comment class
many to one mapping with composite primary keys using #Idclass
#Entity
#IdClass(CommentId.class)
#Table(name = "comments")
public class Comment {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotNull
#Lob
private String text;
#Id
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "post_id", nullable = false)
private Post post;
public Comment() {
}
public Comment(String text) {
this.text = text;
}
//getters and setters
}
Id class
CommentId
public class CommentId implements Serializable {
private static final long serialVersionUID = 1L;
private Post post;
private Long id;
public CommentId(Post post, Long id) {
super();
this.post = post;
this.id = id;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result+ ((post == null) ? 0 : post.hashCode());
result = prime * result ;
return result;
}
public boolean equals(Object object) {
if (object instanceof CommentId) {
CommentId pk = (CommentId)object;
return id.equals(pk.id) && post == pk.post;
} else {
return false;
}
}
//getters and setters
}
repositories
PostRepository
CommentRepository
#Repository
public interface PostRepository extends JpaRepository<Post, Long> {
}
#Repository
public interface CommentRepository extends JpaRepository<Comment, Long>
{
}
Controller class get request and I am using mysql database
#RestController
#RequestMapping("/demo")
public class Controller {
#Autowired
PostRepository ps;
CommentRepository cs;
#GetMapping("/post")
public List<Post> getAll(){
return ps.findAll();
}
#GetMapping("/comment")
public List<Comment> getAllcom(){
return cs.findAll();
}
}

Resources