SSM架构 访问数据库的步骤和代码
时间: 2024-05-02 12:17:05 浏览: 11
SSM架构是指Spring+SpringMVC+MyBatis三个框架的组合,用于开发Java Web应用程序。以下是访问数据库的步骤和代码:
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="root"/>
</bean>
```
2. 配置MyBatis:在Spring中配置MyBatis,指定Mapper文件的位置和命名空间。
```
<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*:com/example/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 {
User selectUserById(int id);
}
```
4. 编写Mapper XML文件:定义SQL语句和参数类型。
```
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectUserById" parameterType="int" resultType="com.example.model.User">
select * from user where id = #{id}
</select>
</mapper>
```
5. 在Service中调用Mapper:在Service中注入Mapper,调用Mapper中定义的方法。
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(int id) {
return userMapper.selectUserById(id);
}
}
```
以上就是SSM架构访问数据库的步骤和代码。