spring整合数据库
时间: 2023-11-21 19:52:31 浏览: 38
Spring整合数据库可以通过Spring Data进行统一处理各种数据库。Spring Data是Spring中与Spring Boot、Spring Cloud等齐名的知名项目,底层也是采用Spring Data的方式来处理数据库。在Spring Boot 2.0以上版本,默认使用Hikari数据源,它是当前Java Web上最优秀的数据源之一。如果需要切换数据源,可以通过配置文件中的spring.datasource.type来指定数据源的类型。通过这些方式,可以实现Spring与数据库的集成。<em>1</em><em>2</em><em>3</em>
#### 引用[.reference_title]
- *1* *2* *3* [10.SpringBoot整合数据库操作](https://blog.csdn.net/qq_44840451/article/details/125275799)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item]
[ .reference_list ]
相关问题
springboot整合springsecurity数据库
要将Spring Security与数据库集成,首先需要添加以下依赖项:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-data</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
</dependency>
```
然后,需要创建一个UserDetails实现类,并实现UserDetailsService接口。这个类将从数据库中获取用户详细信息,并将其返回给Spring Security。
接下来,需要在SecurityConfig类中配置AuthenticationManagerBuilder,以使用上面实现的UserDetailsService来获取用户详细信息。例如,以下代码片段展示了如何将用户详细信息从数据库中获取并进行身份验证:
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
.antMatchers("/**").permitAll()
.and().formLogin().loginPage("/login").permitAll()
.and().logout().logoutSuccessUrl("/login?logout").permitAll()
.and().exceptionHandling().accessDeniedPage("/403");
}
}
```
在这里,我们使用了BCryptPasswordEncoder作为密码编码器,并配置了一个HTTP安全性对象,以指定需要哪些角色才能访问受保护的URL。我们还指定了登录页面和注销成功后跳转的URL,以及拒绝访问页面的URL。
最后,我们需要在数据库中存储用户详细信息。这可以通过使用JdbcTemplate和SQL查询来实现。以下是一个示例查询,用于从数据库中检索用户详细信息:
```
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
String sql = "SELECT username, password, enabled FROM users WHERE username = ?";
List<User> users = jdbcTemplate.query(sql, new String[]{username}, (rs, rowNum) -> new User(
rs.getString("username"),
rs.getString("password"),
rs.getBoolean("enabled"),
true,
true,
true,
AuthorityUtils.createAuthorityList("ROLE_USER")));
if (users.isEmpty()) {
throw new UsernameNotFoundException("User " + username + " not found.");
}
User user = users.get(0);
return new org.springframework.security.core.userdetails.User(
user.getUsername(),
user.getPassword(),
user.isEnabled(),
true,
true,
true,
user.getAuthorities());
}
```
在这里,我们查询名为“users”的数据库表,并使用给定的用户名查找用户。如果找到用户,则创建一个新的UserDetails对象,并将其返回给Spring Security。否则,我们将抛出一个UsernameNotFoundException异常。
总的来说,将Spring Security和数据库集成非常简单。只需要实现UserDetailsService接口,配置AuthenticationManagerBuilder和SecurityConfig,并在数据库中存储用户详细信息即可。
spring整合mybatis操控数据库
Spring 整合 MyBatis 操控数据库可以通过以下步骤完成:
1. 配置数据源:在 Spring 的配置文件中配置数据源,例如:
```
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
```
2. 配置 MyBatis:在 Spring 的配置文件中配置 MyBatis,例如:
```
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="typeAliasesPackage" value="com.example.model" />
<property name="mapperLocations" value="classpath:mapper/*.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper" />
</bean>
```
3. 编写 Mapper:创建 Mapper 接口并编写 SQL 语句,例如:
```
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(Long id);
@Insert("INSERT INTO user (name, age) VALUES (#{name}, #{age})")
int insert(User user);
@Update("UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}")
int update(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
int delete(Long id);
}
```
4. 注入 Mapper:在 Service 层中注入 Mapper 并调用相应方法,例如:
```
@Autowired
private UserMapper userMapper;
public User findById(Long id) {
return userMapper.findById(id);
}
public int insert(User user) {
return userMapper.insert(user);
}
public int update(User user) {
return userMapper.update(user);
}
public int delete(Long id) {
return userMapper.delete(id);
}
```
完成以上步骤后,就可以通过 Service 层的方法操控数据库了。例如:
```
User user = userService.findById(1L);
System.out.println(user.getName());
User newUser = new User();
newUser.setName("Tom");
newUser.setAge(20);
userService.insert(newUser);
newUser.setAge(30);
userService.update(newUser);
userService.delete(2L);
```
这样就可以查询、新增、修改和删除数据库中的数据了。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)