Spring Framework Tutorial

Software Setup and Configuration (STS/Eclipse/IntelliJ)

Core Spring

Spring Annotations

Spring Data

Spring JDBC

Spring Security

Spring Data JPA - Insert Data in MySQL Table

Using Spring Data JPA to insert data into a MySQL table is straightforward. Let's go step by step:

  • Setting Up the Spring Boot Project: Create a Spring Boot project using the Spring Initializr or your preferred IDE, adding the Spring Web, Spring Data JPA, and MySQL Driver dependencies.

  • Configure MySQL Database: In application.properties (or application.yml), configure your MySQL datasource:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=rootpassword
spring.jpa.hibernate.ddl-auto=update
  • Define the Entity:

Define your entity class to map to your MySQL table:

@Entity
@Table(name="employees")
public class Employee {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String role;

    // Constructors, getters, setters...
}

In this example, the Employee class maps to the "employees" table in the MySQL database.

  • Create the Repository:

Spring Data JPA provides the JpaRepository interface that contains methods for standard CRUD operations:

public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}
  • Insert Data:

With the repository set up, you can now insert data:

  • Via Service/Controller:
@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

    public Employee addEmployee(Employee employee) {
        return employeeRepository.save(employee);
    }
}

Now, invoking the addEmployee method will insert a new Employee record into the database:

Employee newEmployee = new Employee();
newEmployee.setName("John Doe");
newEmployee.setRole("Developer");
employeeService.addEmployee(newEmployee);
  • Test Your Insertion:

You can either create a REST API using a Spring Controller to test the insertion or use a command-line runner to insert data on startup. Ideally, you'd also want to write integration tests to ensure everything is functioning as expected.

Remember, using employeeRepository.save(entity) will either insert a new record (if it doesn't exist) or update an existing record (if it exists, based on its primary key).

  1. Inserting data into MySQL table using Spring Data JPA:

    • Use the save method provided by Spring Data JPA repositories to insert data into a MySQL table.
    // UserRepository.java
    import org.springframework.data.repository.CrudRepository;
    
    public interface UserRepository extends CrudRepository<User, Long> {
    
        User save(User user);
    }
    
  2. How to save entities with Spring Data JPA in MySQL:

    • Save entities using the save method, which handles both insertion and update operations based on the existence of the primary key.
    // ProductRepository.java
    import org.springframework.data.repository.CrudRepository;
    
    public interface ProductRepository extends CrudRepository<Product, Long> {
    
        Product save(Product product);
    }
    
  3. Persisting records with Spring Data JPA in MySQL database:

    • Use the save method for persisting records into a MySQL database using Spring Data JPA.
    // OrderRepository.java
    import org.springframework.data.repository.CrudRepository;
    
    public interface OrderRepository extends CrudRepository<Order, Long> {
    
        Order save(Order order);
    }
    
  4. Inserting multiple records with Spring Data JPA in MySQL:

    • Save a collection of entities to insert multiple records into a MySQL table.
    // ProductRepository.java
    import org.springframework.data.repository.CrudRepository;
    
    public interface ProductRepository extends CrudRepository<Product, Long> {
    
        Iterable<Product> saveAll(Iterable<Product> products);
    }
    
  5. Generated keys and save methods in Spring Data JPA for MySQL:

    • Work with auto-generated keys by annotating the primary key field with @GeneratedValue and using the save method.
    // Product.java
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    
    @Entity
    public class Product {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long productId;
    
        // Other fields and methods...
    }
    
  6. Bulk insert operations in Spring Data JPA for MySQL:

    • Perform bulk insert operations using the saveAll method to insert a collection of entities.
    // UserRepository.java
    import org.springframework.data.repository.CrudRepository;
    
    public interface UserRepository extends CrudRepository<User, Long> {
    
        Iterable<User> saveAll(Iterable<User> users);
    }
    
  7. Cascade persist with Spring Data JPA and MySQL:

    • Use the cascade attribute to enable the cascade persist behavior, allowing associated entities to be persisted automatically.
    // Order.java
    import javax.persistence.CascadeType;
    import javax.persistence.OneToMany;
    
    @Entity
    public class Order {
    
        @OneToMany(mappedBy = "order", cascade = CascadeType.PERSIST)
        private List<OrderItem> orderItems;
    
        // Other fields and methods...
    }
    
  8. Customized insert queries in Spring Data JPA for MySQL:

    • Customize insert queries using the @Query annotation to execute custom SQL or JPQL statements.
    // UserRepository.java
    import org.springframework.data.jpa.repository.Query;
    import org.springframework.data.repository.CrudRepository;
    
    public interface UserRepository extends CrudRepository<User, Long> {
    
        @Query("INSERT INTO User (name, email) VALUES (?1, ?2)")
        void insertUser(String name, String email);
    }