MyBatis是一种支持自定义SQL、存储过程和高级映射的持久层框架。下面是一个简单的Java MyBatis配置示例:
- 首先,需要添加MyBatis的依赖到项目的pom.xml文件中:
<dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.6</version>
</dependency>
- 接下来,在项目的src/main/resources目录下创建一个名为mybatis-config.xml的文件,用于配置MyBatis的全局设置:
<?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="password" /></dataSource></environment></environments><mappers><mapper resource="com/example/mapper/MyMapper.xml" /></mappers>
</configuration>
注意:上述配置中需要根据实际情况修改数据库相关的配置。
- 创建一个接口,用于定义数据库操作的方法,例如:
package com.example.mapper;import com.example.model.User;public interface UserMapper {User getUserById(int id);void addUser(User user);void updateUser(User user);void deleteUser(int id);
}
- 创建一个XML文件,用于映射接口中的方法到SQL语句,例如:
<?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.mapper.UserMapper"><select id="getUserById" parameterType="int" resultType="com.example.model.User">SELECT * FROM users WHERE id = #{id}</select><insert id="addUser" parameterType="com.example.model.User">INSERT INTO users (name, age) VALUES (#{name}, #{age})</insert><update id="updateUser" parameterType="com.example.model.User">UPDATE users SET name = #{name}, age = #{age} WHERE id = #{id}</update><delete id="deleteUser" parameterType="int">DELETE FROM users WHERE id = #{id}</delete>
</mapper>
- 在Java代码中使用MyBatis进行数据库操作,例如:
import com.example.mapper.UserMapper;
import com.example.model.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;
import java.io.Reader;public class Main {public static void main(String[] args) {try {// 读取MyBatis配置文件Reader reader = Resources.getResourceAsReader("mybatis-config.xml");// 创建SqlSessionFactorySqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);// 创建SqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();// 获取Mapper接口的实现类UserMapper userMapper = sqlSession.getMapper(UserMapper.class);// 调用Mapper接口的方法进行数据库操作User user = userMapper.getUserById(1);System.out.println(user);// 提交事务sqlSession.commit();// 关闭SqlSessionsqlSession.close();} catch (IOException e) {e.printStackTrace();}}
}
上述示例中通过MyBatis的SqlSessionFactory创建了一个SqlSession对象,通过该对象可以获取到Mapper接口的实现类,然后可以调用Mapper接口的方法进行数据库操作。最后需要注意在操作完成后提交事务并关闭SqlSession。