• ADADADADAD

    spring整合mybatis实现增删改查操作[ 编程知识 ]

    编程知识 时间:2024-11-20 12:52:50

    作者:文/会员上传

    简介:

    首先确保在pom.xml中添加spring和mybatis的依赖:<dependencies><!-- Spring --><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactI

    以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。

      首先确保在pom.xml中添加spring和mybatis的依赖:
    <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的SqlSessionFactory和MapperScannerConfigurer:
    <!-- 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>
      创建MyBatis的映射文件和Mapper接口:
    <!-- 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的方法}
      创建User类作为实体类:
    // com/example/model/User.javapackage com.example.model;public class User {private int id;private String name;private int age;// 省略getter和setter方法}
      编写Service类调用Mapper接口实现增删改查操作:
    // 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接口实现具体的数据库操作。

    spring整合mybatis实现增删改查操作.docx

    将本文的Word文档下载到电脑

    推荐度:

    下载
    热门标签: Springmybatis