Here's an example of how you might integrate Microsoft SQL Server and Hibernate in a Spring Boot application:
- First, add the following dependencies to your
pom.xmlfile:
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
- Next, define your entity class and annotate it with JPA annotations:
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class User {
@Id
private Long id;
private String name;
private int age;
// getters and setters
}
- Define a repository interface to interact with the Microsoft SQL Server database:
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findByName(String name);
}
- In your application configuration file (
application.properties), configure the connection to Microsoft SQL Server:
spring.datasource.url=jdbc:sqlserver://localhost;databaseName=test
spring.datasource.username=<your_username>
spring.datasource.password=<your_password>
spring.jpa.show-sql=true
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServerDialect
spring.jpa.hibernate.ddl-auto=create-drop
- Finally, in your main class, you can use the repository to perform CRUD operations on the User entity:
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
CommandLineRunner init(UserRepository repository) {
return args -> {
repository.deleteAll();
repository.save(new User(1L, "John", 25));
repository.save(new User(2L, "Jane", 30));
repository.save(new User(3L, "Jim", 35));
System.out.println("Users found with findAll():");
System.out.println("-------------------------------");
for (User user : repository.findAll()) {
System.out.println(user);
}
System.out.println();
System.out.println("User found with findByName('Jane'):");
System.out.println("--------------------------------");
System.out.println(repository.findByName("Jane"));
};
No comments:
Post a Comment