ssm数据库连接与访问
时间: 2023-10-24 18:21:37 浏览: 48
SSM(Spring + SpringMVC + MyBatis)是一种常用的Java Web开发框架,其中MyBatis是一种优秀的持久层框架,可以用来连接和访问数据库。
下面是连接和访问数据库的步骤:
1. 引入MyBatis的依赖,可以在Maven中添加以下依赖:
```xml
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.x.x</version>
</dependency>
```
2. 配置数据源,可以在Spring的配置文件中配置数据源,例如使用Druid连接池:
```xml
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
```
3. 配置MyBatis的SqlSessionFactory,可以使用Spring提供的SqlSessionFactoryBean:
```xml
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
```
4. 配置MyBatis的Mapper,可以使用MapperScannerConfigurer:
```xml
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.mapper"/>
</bean>
```
其中,`com.example.mapper`是Mapper接口所在的包。
5. 编写Mapper接口和Mapper.xml文件,例如:
```java
public interface UserMapper {
User selectUserById(int id);
}
```
```xml
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectUserById" resultType="com.example.entity.User">
select * from user where id = #{id}
</select>
</mapper>
```
6. 在Service中调用Mapper接口,例如:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(int id) {
return userMapper.selectUserById(id);
}
}
```
以上就是SSM连接和访问数据库的基本步骤。当然,在实际开发中还需要处理事务、异常等问题。