spring使用mybatis连接数据库 方式2

标题官方文档

在这里插入图片描述

  • 修改配置
public class UserDaoImpl extends SqlSessionDaoSupport implements UserMapper {
    public List<User> selectUser() {
        UserMapper mapper = getSqlSession().getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}
  • bean
<bean id="userDao" class="com.kuang.dao.UserDaoImpl">
    <property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
  • 测试
 @Test
    public void test2(){
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        userMapper userMapper = context.getBean("userMapper2", userMapper.class);
        for (User user : userMapper.selectUser()) {
            System.out.println(user);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
使用Mybatis连接数据库的步骤如下: 1. 添加MybatisMybatis-Spring的依赖 ```xml <!-- Mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> ``` 2. 配置数据源 在`application.properties`中配置数据源的属性,例如: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.jdbc.Driver ``` 3. 创建Mapper接口和SQL语句 Mapper接口是指定SQL语句的接口。可以使用注解或XML来指定SQL语句。 例如,创建一个UserMapper接口和XML文件: UserMapper.java ```java @Mapper public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User findById(long id); } ``` UserMapper.xml ```xml <mapper namespace="com.example.mapper.UserMapper"> <select id="findById" resultType="com.example.model.User"> SELECT * FROM user WHERE id = #{id} </select> </mapper> ``` 4. 注册Mapper接口 在启动类中添加`@MapperScan`注解,指定Mapper接口所在的包: ```java @SpringBootApplication @MapperScan("com.example.mapper") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 5. 使用Mapper接口进行数据操作 在需要使用Mapper接口的地方注入即可,例如: ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User findById(long id) { return userMapper.findById(id); } } ``` 以上就是在Spring Boot中使用Mybatis连接数据库的步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小小徐404

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值