12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
ADADADADAD
编程知识 时间:2024-11-20 12:52:50
作者:文/会员上传
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
12-09
首先确保在pom.xml中添加spring和mybatis的依赖:<dependencies><!-- Spring --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactI
以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。
<dependencies><!-- Spring --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>5.2.5.RELEASE</version></dependency><!-- MyBatis --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.3</version></dependency></dependencies>
<!-- MyBatis配置文件 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="configLocation" value="classpath:mybatis-config.xml" /></bean><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><property name="basePackage" value="com.example.mapper" /></bean>
<!-- com/example/mapper/UserMapper.xml --><mapper namespace="com.example.mapper.UserMapper"><select id="selectUserById" resultType="com.example.model.User">SELECT * FROM user WHERE id = #{id}</select><insert id="insertUser" parameterType="com.example.model.User">INSERT INTO user(name, age) VALUES(#{name}, #{age})</insert><!-- 同理,添加update和delete的SQL语句 --></mapper>
// com/example/mapper/UserMapper.javapackage com.example.mapper;import com.example.model.User;public interface UserMapper {User selectUserById(int id);void insertUser(User user);// 添加update和delete的方法}
// com/example/model/User.javapackage com.example.model;public class User {private int id;private String name;private int age;// 省略getter和setter方法}
// com/example/service/UserService.javapackage com.example.service;import com.example.mapper.UserMapper;import com.example.model.User;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;@Servicepublic class UserService {@Autowiredprivate UserMapper userMapper;public User getUserById(int id) {return userMapper.selectUserById(id);}public void addUser(User user) {userMapper.insertUser(user);}// 添加update和delete的方法}
至此,就完成了Spring整合MyBatis实现增删改查操作的基本步骤。通过配置MyBatis的SqlSessionFactory和MapperScannerConfigurer,以及编写Mapper接口和映射文件,再通过Service类调用Mapper接口实现具体的数据库操作。
11-20
11-19
11-20
11-20
11-20
11-19
11-20
11-20
11-19
11-20
11-19
11-19
11-19
11-19
11-19
11-19