/* NOTE: This is Spring JPA and NOT SPRING DATA JPA
* Spring JPA uses EntityManager to handle entity management
* Spring Data JPA uses a layer of abstraction which further simplifies this process
*/

// application.properties
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.show-sql=true // this will show the sql equivalence of JPA operations behind the scene in console

// Course.java
@Entity(name="Course") // name of the table which this class will be mapped with
public class Course {
	@Id // primary key column
	private long id;
	@Column(name="name") // name of the column that this attribute will be mapped to
	private String name;
	@Column(name="author")
	private String author;

	public Course() {}

	public Course(long id, String name, String author) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
	}

	// setters
	// getters
	// toString

}

// CourseJpaRepository.java
@Repository
@Transactional
public class CourseJpaRepository {
	
	@PersistenceContext // Alternative to @Autowired
	private EntityManager entityManager; // this will be responsible to manage the operations
	
	public void insert(Course course) {
		entityManager.merge(course); // .merge() is used to insert
	}
	
	public Course findById(long id) {
		return entityManager.find(Course.class, id);
	}

	public void deleteById(long id) { // There is no direct way of deletion. First you need to find the item and remove the object next
		Course course = entityManager.find(Course.class, id);
		entityManager.remove(course);
	}

}

// CourseCommandLineRunner.java that makes sure to run everything on startup
@Component
public class CourseCommandLineRunner implements CommandLineRunner{

	@Autowired
	private CourseJpaRepository repository;
	
	@Override
	public void run(String... args) throws Exception {
		// Insert operations
		repository.insert(new Course(1, "Learn AWS!", "Udemy"));
		repository.insert(new Course(2, "Learn Azure!", "Udemy"));
		repository.insert(new Course(3, "Learn GCP!", "Udemy"));
		// Delete operation
		repository.deleteById(1);
		// Read operations
		System.out.println(repository.findById(2));
		System.out.println(repository.findById(3));
	}
}/* NOTE: This is SPRING DATA JPA and NOT SPRING JPA
* While Spring JPA uses EntityManager to handle entity management
* Spring Data JPA uses a layer of abstraction which further simplifies this process
*  It extends JpaRepository that helps to run EntityManager behind simple interface without directly using it
*/

// application.properties
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.jpa.show-sql=true // this will show the sql equivalence of JPA operations behind the scene in console

// Course.java
@Entity(name="Course") // name of the table which this class will be mapped with
public class Course {
	@Id // primary key column
	private long id;
	@Column(name="name") // name of the column that this attribute will be mapped to
	private String name;
	@Column(name="author")
	private String author;

	public Course() {}

	public Course(long id, String name, String author) {
		super();
		this.id = id;
		this.name = name;
		this.author = author;
	}

	// setters
	// getters
	// toString

}

// CourseSpringDataJpaRepository.java
public interface CourseSpringDataJpaRepository extends JpaRepository<Course, Long>{
	
	List<Course> findByAuthor(String author); // custom read method signature, findBy...FieldNameFromEntity
	List<Course> findByName(String name); // custom read method signature, findBy...FieldNameFromEntity

}

// CourseCommandLineRunner.java that makes sure to run everything on startup
@Component
public class CourseCommandLineRunner implements CommandLineRunner{

	@Autowired
	private CourseSpringDataJpaRepository repository;
	
	@Override
	public void run(String... args) throws Exception {
        // Insert operation
		repository.save(new Course(1, "Learn AWS !", "Udemy"));
		repository.save(new Course(2, "Learn Azure !", "Udemy"));
		repository.save(new Course(3, "Learn DevOps !", "Udemy"));
		// Delete operation
		repository.deleteById(1l);
		// Read Operation
		System.out.println(repository.findById(2l)); // 2 long type value
		System.out.println(repository.findAll());
		System.out.println(repository.count());
		// Custom read operations
		System.out.println(repository.findByAuthor("Udemy"));
		System.out.println(repository.findByName("Learn AWS !"));
	}
}

Java相关代码片段

array class methods in java

how to read all line from file java

Java int length

intent example in android

how to doubling size of an arrays in java

how to find my jdk path

how to handle multiple throws exception in java

spring boot jdbc for postgrest

factorial of a number

types of typecasting in java

types of assignment statement in java

Thread mutex

env files in spring boot

java over loading

logging in spring boot

how to split a list in multiple lists java

can two servlet have same urlpattern

spring debug

jsp spring

hanoi tower recursion java

java equals

age difference java

sed cheat sheet

java compare method

how to make a activity default in manifest

java max memory size

yum uninstall java

timestamp to long java

how to set background image in android studio

simple calculator in android

When to use HashMap vs Map

spring boot jpa

spring data jpa

spring jdbc

jpa vs hibernate

java with checking the password matching

profile in spring boot

string templates java

spring rest controller

java arraylist get item

com.oracle.jdbc

check if map is not empty java

how to install java 8 on debian 12

regex caractères spéciaux java

java 11 yum install

manage session in redis spring boot

java: error: release version 19 not supported

bean scope in spring

xml configuration in spring

spring cdi annotations

postconstruct and predestroy in spring

java decode_message

spring lazy initialization

java decorator design pattern

dependency injection in spring

check back pressed in fragment andorid

send email to any domain using java

record java

vs code setup for input/output in java

substring java

receive second word in string java

loose coupling in java

default value of char in java

spring boot repository pattern

spring boot h2 database

add security to spring admin

java islessthan method

Java implementation of recursive Binary Search

java round double

java downcasting

range of fibonacci series in java using recursion

java by anyone

solid java

equals() and hashcode() methods in java

android java map to bundle

android start activity with data

medium java 17

java import util list

bean life cycle in spring

spring boot aop