设计一个使用SSM(spring+springmvc+mybatis)sql文件
时间: 2024-01-14 12:02:46 浏览: 90
ssm项目spring+springmvc+mybatis+mysql
首先,需要在Mybatis的配置文件中定义Mapper接口的位置和SQL映射文件的位置:
```
<configuration>
<mappers>
<mapper class="com.example.dao.UserMapper"/>
</mappers>
<properties>
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</properties>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
</configuration>
```
然后,在Mapper接口中定义SQL语句的方法:
```
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User getUserById(@Param("id") int id);
@Insert("INSERT INTO user (username, password) VALUES (#{username}, #{password})")
void insertUser(User user);
@Update("UPDATE user SET username = #{username}, password = #{password} WHERE id = #{id}")
void updateUser(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
void deleteUser(@Param("id") int id);
}
```
最后,在Spring的配置文件中,使用MapperScannerConfigurer扫描Mapper接口的包路径:
```
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.dao"/>
</bean>
```
这样,就可以在Service层中注入Mapper接口,调用对应的方法来操作数据库了。
阅读全文