Hibernate: SQL query, JPQL, Hibernate named query, JPA Streamer

 1. Native query on Hibernate

package com.example.relationships.entity;

import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import lombok.*;
import org.hibernate.Hibernate;

import java.util.Objects;

@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Entity
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
Student student = (Student) o;
return id != null && Objects.equals(id, student.id);
}

@Override
public int hashCode() {
return getClass().hashCode();
}
}
package com.example.relationships.repository;

import com.example.relationships.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface StudentRepository extends JpaRepository<Student, Long> {

List<Student> findAllByAgeGreaterThan(int age);

@Query(value = "select * from student where student.age > ?", nativeQuery = true)
List<Student> getStudentsByAgeGreaterThan(int age);
}
package com.example.relationships;

import com.example.relationships.entity.Student;
import com.example.relationships.repository.StudentRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@RequiredArgsConstructor
public class RelationshipsApplication implements CommandLineRunner {

private final StudentRepository studentRepsitory;

public static void main(String[] args) {
SpringApplication.run(RelationshipsApplication.class, args);
}

@Override
// @Transactional
public void run(String... args) throws Exception {
System.out.println("Start--------------------------------------------------");

for (int i = 0; i < 10; i++) {
Student s = new Student();
s.setName("Test " + i);
s.setAge(13 + i);
studentRepsitory.save(s);
}

studentRepsitory.getStudentsByAgeGreaterThan(16).stream().forEach(System.out::println);

System.out.println("Finish--------------------------------------------------");
}
}

Start----------------------------------------------------

Hibernate: select * from student where student.age > ?

Student(id=5, name=Test 4, age=17)

Student(id=6, name=Test 5, age=18)

Student(id=7, name=Test 6, age=19)

Student(id=8, name=Test 7, age=20)

Student(id=9, name=Test 8, age=21)

Student(id=10, name=Test 9, age=22)

Finish--------------------------------------------------


-------------------

package com.example.relationships.repository;

import com.example.relationships.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface StudentRepository extends JpaRepository<Student, Long> {

List<Student> findAllByAgeGreaterThan(int age);

@Query(value = "select * from student where student.age > ?", nativeQuery = true)
List<Student> getStudentsByAgeGreaterThan(int age);

@Modifying
@Query(value = "update student set name = ?2 where id = ?1", nativeQuery = true)
Integer updateStudentNameById(int id, String name);
}
package com.example.relationships;

import com.example.relationships.entity.Student;
import com.example.relationships.repository.StudentRepository;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@RequiredArgsConstructor
public class RelationshipsApplication implements CommandLineRunner {

private final StudentRepository studentRepository;

public static void main(String[] args) {
SpringApplication.run(RelationshipsApplication.class, args);
}

@Override
@Transactional
public void run(String... args) throws Exception {
System.out.println("Start----------------------------------------------------");

for (int i = 0; i < 10; i++) {
Student s = new Student();
s.setName("Test " + i);
s.setAge(13 + i);
studentRepository.save(s);
}

System.out.println("Start----------------------------------------------------");

Integer id = studentRepository.updateStudentNameById(5, "Parvin");
System.out.println(id);

System.out.println("Finish--------------------------------------------------");
}
}


Start----------------------------------------------------

Hibernate: update student set name = ? where id = ?

1

Finish--------------------------------------------------

Buradaki Integer cavabi bize nece row deyishildiyini gosterir.


2. JPQL - Java Persistence Query Language

package com.example.relationships.repository;

import com.example.relationships.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface StudentRepository extends JpaRepository<Student, Long> {

List<Student> findAllByAgeGreaterThan(int age);

@Query(value = "select * from student s where s.age > ?", nativeQuery = true)
List<Student> getStudentsByAgeGreaterThan(int age);

@Modifying
@Query(value = "update student s set name = ?2 where s.id = ?1", nativeQuery = true)
Integer updateStudentNameById(int id, String name);

@Query(value = "select s from Student s where s.age > ?1")
List<Student> getStudentsByAgeGreaterThanJPQL(int age);
}
package com.example.relationships.repository;

import com.example.relationships.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface StudentRepository extends JpaRepository<Student, Long> {

List<Student> findAllByAgeGreaterThan(int age);

@Query(value = "select * from student where student.age > ?", nativeQuery = true)
List<Student> getStudentsByAgeGreaterThan(int age);

@Modifying
@Query(value = "update student set name = ?2 where id = ?1", nativeQuery = true)
Integer updateStudentNameById(int id, String name);

@Query(value = "select s from Student s where s.age > ?1")
List<Student> getStudentsByAgeGreaterThanJPQL(int age);
}


3. Hibernate named query

package com.example.relationships.entity;

import jakarta.persistence.*;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.Hibernate;

import java.util.Objects;

@Getter
@Setter
@ToString
@RequiredArgsConstructor
@Entity
@NamedQueries({@NamedQuery(name = "selectStudentById", query = "select s from Student s where s.id = :id")})
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private Integer age;

@OneToOne(cascade = CascadeType.PERSIST, orphanRemoval = true, fetch = FetchType.LAZY)
@JoinColumn(name = "address_id")
private Address address;

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
Student student = (Student) o;
return id != null && Objects.equals(id, student.id);
}

@Override
public int hashCode() {
return getClass().hashCode();
}
}


package com.example.relationships;

import com.example.relationships.entity.Address;
import com.example.relationships.entity.Student;
import com.example.relationships.repository.StudentRepository;
import jakarta.persistence.EntityManagerFactory;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@RequiredArgsConstructor
public class RelationshipsApplication implements CommandLineRunner {

private final EntityManagerFactory entityManagerFactory;
private final StudentRepository studentRepository;

public static void main(String[] args) {
SpringApplication.run(RelationshipsApplication.class, args);
}

@Override
@Transactional
public void run(String... args) throws Exception {
System.out.println("Start----------------------------------------------------");

Address address = new Address();
address.setEmail("test@gmail.com");

Student parvin = new Student();
parvin.setName("Parvin");
parvin.setAge(31);
parvin.setAddress(address);

studentRepository.save(parvin);

System.out.println("Start----------------------------------------------------");

SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
Session session = sessionFactory.openSession();
session.beginTransaction();
Query query = session.getNamedQuery("selectStudentById").setParameter("id", 1L);
Student student = (Student) query.uniqueResult();
sessionFactory.close();
System.out.println(student);
System.out.println("Finish--------------------------------------------------");
}
}


4. JPA Streamer

plugins {
id 'java'
id 'org.springframework.boot' version '3.1.2'
id 'io.spring.dependency-management' version '1.1.2'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'

java {
sourceCompatibility = '17'
}

configurations {
compileOnly {
extendsFrom annotationProcessor
}
}

repositories {
mavenCentral()
}

dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'

// jpa streamer
implementation 'com.speedment.jpastreamer:jpastreamer-core:3.0.3'
annotationProcessor 'com.speedment.jpastreamer:fieldgenerator-standard:3.0.3'
}

tasks.named('test') {
useJUnitPlatform()
}


package com.example.relationships;

import com.example.relationships.entity.Student;
import com.example.relationships.entity.Student$;
import com.example.relationships.repository.StudentRepository;
import com.speedment.jpastreamer.application.JPAStreamer;
import jakarta.persistence.EntityManagerFactory;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@RequiredArgsConstructor
public class RelationshipsApplication implements CommandLineRunner {

private final EntityManagerFactory entityManagerFactory;
private final StudentRepository studentRepository;

public static void main(String[] args) {
SpringApplication.run(RelationshipsApplication.class, args);
}

@Override
@Transactional
public void run(String... args) throws Exception {
System.out.println("Start----------------------------------------------------");

JPAStreamer jpaStreamer = JPAStreamer.of(entityManagerFactory);

// for (int i = 1; i < 11; i++) {
// Student student = new Student();
// student.setName("Test " + i);
// student.setAge(10 + i);
// studentRepository.save(student);
// }

jpaStreamer.stream(Student.class)
.filter(Student$.age.greaterThan(15))
.forEach(System.out::println);

System.out.println("Finish--------------------------------------------------");
}
}









































Комментарии

Популярные сообщения из этого блога

IoC:ApplicationContext, BeanFactory. Bean

Lesson1: JDK, JVM, JRE

Lesson_2: Operations in Java