MyBatis是一种Java持久化框架,用于简化与关系数据库的交互。它提供了一种将SQL语句与Java代码进行解耦的方式,通过XML配置文件或注解来定义和映射SQL语句,从而实现了对象关系映射(ORM)。
MyBatis与MySQL数据库的连接可以通过以下几个步骤完成:
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydatabase"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/MyMapper.xml"/>
</mappers>
</configuration>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.MyMapper">
<select id="getUserById" resultType="com.example.User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
public interface MyMapper {
User getUserById(Long id);
}
然后,在对应的DAO实现类中编写方法的具体实现:
@Repository
public class MyMapperImpl implements MyMapper {
private final SqlSessionFactory sqlSessionFactory;
public MyMapperImpl(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public User getUserById(Long id) {
try (SqlSession session = sqlSessionFactory.openSession()) {
return session.selectOne("com.example.MyMapper.getUserById", id);
}
}
}
这样,就可以通过MyBatis与MySQL数据库建立连接,并执行相应的SQL语句进行数据库操作。
推荐的腾讯云相关产品:腾讯云数据库MySQL。腾讯云数据库MySQL(TencentDB for MySQL)是腾讯云提供的一种高可用、可扩展、全面兼容的关系型数据库服务。它提供了自动备份、容灾切换、监控报警等功能,支持弹性扩容和性能优化,适用于各种规模的应用场景。
腾讯云产品介绍链接地址:腾讯云数据库MySQL
领取专属 10元无门槛券
手把手带您无忧上云