data base spring
- Define Entity Class:
- Create a Java class annotated with
@Entity
to represent the database table. - Use annotations such as
@Id
for primary key and@Column
for other columns.
@Entity
public class YourEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "column_name")
private String columnName;
// Other fields and methods
}
- Create Repository Interface:
- Declare a repository interface by extending
JpaRepository
or its subinterface. - Specify the entity type and the type of the primary key.
public interface YourEntityRepository extends JpaRepository<YourEntity, Long> {
// Custom queries or methods can be defined here
}
- Configure Database Properties:
- Update
application.properties
orapplication.yml
with database connection details.
spring.datasource.url=jdbc:mysql://localhost:3306/your_database
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- Enable JPA and Repository Scanning:
- Annotate the main application class with
@SpringBootApplication
. - Ensure that the package containing the main class is scanned for components.
@SpringBootApplication
@ComponentScan(basePackages = "com.your.package")
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
- Use Repository in Service or Controller:
- Autowire the repository in your service or controller class for database operations.
@Service
public class YourEntityService {
@Autowired
private YourEntityRepository yourEntityRepository;
// Methods using the repository for database operations
}
- Run Application and Test:
- Start your Spring Boot application.
Use Postman, curl, or any other tool to test your REST endpoints or services.
Hibernate Auto DDL Configuration (Optional):
- Configure Hibernate to automatically generate and update database schema.
spring.jpa.hibernate.ddl-auto=update
- Transaction Management (Optional):
- Annotate service methods with
@Transactional
for proper transaction management.
@Service
@Transactional
public class YourEntityService {
// Service methods with database operations
}
- DTOs (Data Transfer Objects) Usage (Optional):
- Create DTOs to transfer data between layers, especially when exposing APIs.
public class YourEntityDTO {
// Fields representing data to be transferred
}
- Handle Exceptions (Optional):
- Implement exception handling for database-related errors.
@ControllerAdvice
public class ExceptionHandlerController {
@ExceptionHandler(DataAccessException.class)
public ResponseEntity<Object> handleDataAccessException(DataAccessException ex) {
// Handle the exception and return an appropriate response
}
}