pom.xml
文件中添加以下依赖:,,``xml,,org.mybatis,mybatis,3.5.6,,,mysql,mysql-connector-java,8.0.23,,
`,,2. **配置 MyBatis**:您需要配置 MyBatis。这通常涉及创建一个
mybatis-config.xml 文件,该文件位于类路径的根目录下。在这个文件中,您需要指定数据库连接信息,URL、用户名和密码。,,
`xml,,,,,,,,,,,,,,,,,,,
`,,3. **创建 Mapper 接口和 XML 文件**:MyBatis 使用 Mapper 接口和 XML 文件来定义 SQL 语句。您需要为每个表或操作创建一个 Mapper 接口和一个对应的 XML 文件。假设您有一个用户表,您可以创建一个
UserMapper.java 接口和一个
UserMapper.xml 文件。,,
`java,package com.example.mapper;,,import com.example.model.User;,import java.util.List;,,public interface UserMapper {, User selectUserById(int id);, List selectAllUsers();, void insertUser(User user);, void updateUser(User user);, void deleteUser(int id);,},
`,,
`xml,,,,, SELECT * FROM users WHERE id = #{id},,, SELECT * FROM users,,, INSERT INTO users (name, email) VALUES (#{name}, #{email}),,, UPDATE users SET name=#{name}, email=#{email} WHERE id=#{id},,, DELETE FROM users WHERE id=#{id},,,
`,,4. **使用 MyBatis**:您可以在代码中使用 MyBatis。您需要获取
SqlSessionFactory 实例,然后通过它获取
SqlSession 实例。使用
SqlSession 实例,您可以执行 CRUD 操作。,,
`java,package com.example;,,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.InputStream;,import java.util.List;,,public class MyApp {, public static void main(String[] args) throws Exception {, String resource = "mybatis-config.xml";, InputStream inputStream = Resources.getResourceAsStream(resource);, SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);,, try (SqlSession session = sqlSessionFactory.openSession()) {, UserMapper mapper = session.getMapper(UserMapper.class);, User user = mapper.selectUserById(1);, System.out.println(user);,, List users = mapper.selectAllUsers();, users.forEach(System.out::println);,, User newUser = new User("John Doe", "john@example.com");, mapper.insertUser(newUser);, session.commit();,, newUser.setName("Jane Doe");, mapper.updateUser(newUser);, session.commit();,, mapper.deleteUser(newUser.getId());, session.commit();, }, },},
``Powered By Z-BlogPHP 1.7.3