Teach you step by step how to write a MyBatis introductory program: easily master the core skills
Introduction:
MyBatis is a popular persistence layer framework, which can help us more Interact with the database conveniently. This article will be based on a simple example and teach you step by step how to write an introductory program for MyBatis, allowing you to easily master the core skills. During the writing process, we will use Java as the programming language and the MySQL database as an example.
1. Environment preparation
Before starting, we need to prepare the following environment:
2. Create a Maven project
<dependencies> <!-- MyBatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <!-- MySQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> </dependencies>
3. Write the database configuration file
<configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai"/> <property name="username" value="your_username"/> <property name="password" value="your_password"/> </dataSource> </environment> </environments> <mappers> <mapper resource="mapper/UserMapper.xml"/> </mappers> </configuration>
Pay attention to replacing the value
attribute in the <property>
tag Information about your own database.
4. Write the POJO class corresponding to the data table
public class User { private int id; private String name; private int age; // 省略getter和setter方法 }
2. Write the Mapper interface and mapping file
public interface UserMapper { public User getUserById(int id); public List<User> getAllUsers(); public void addUser(User user); public void updateUser(User user); public void deleteUser(int id); }
<!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.pojo.User"> SELECT * FROM user WHERE id = #{id} </select> <select id="getAllUsers" resultType="com.example.pojo.User"> SELECT * FROM user </select> <insert id="addUser" parameterType="com.example.pojo.User"> INSERT INTO user (name, age) VALUES (#{name}, #{age}) </insert> <update id="updateUser" parameterType="com.example.pojo.User"> UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id} </update> <delete id="deleteUser" parameterType="int"> DELETE FROM user WHERE id = #{id} </delete> </mapper>
5. Write test code
public class App { public static void main(String[] args) { // 创建SqlSessionFactory对象 InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); try { // 获取UserMapper接口的实例 UserMapper userMapper = sqlSession.getMapper(UserMapper.class); // 测试getUserById方法 User user = userMapper.getUserById(1); System.out.println(user.getId() + " " + user.getName() + " " + user.getAge()); // 测试getAllUsers方法 List<User> userList = userMapper.getAllUsers(); for (User u : userList) { System.out.println(u.getId() + " " + u.getName() + " " + u.getAge()); } // 测试addUser方法 User newUser = new User(); newUser.setName("张三"); newUser.setAge(20); userMapper.addUser(newUser); sqlSession.commit(); // 测试updateUser方法 User updateUser = new User(); updateUser.setId(1); updateUser.setName("李四"); updateUser.setAge(25); userMapper.updateUser(updateUser); sqlSession.commit(); // 测试deleteUser方法 userMapper.deleteUser(1); sqlSession.commit(); } finally { sqlSession.close(); } } }
6. Run the program
Conclusion:
Through the study of this article, I believe you have easily mastered the core skills of MyBatis. I hope you can use MyBatis in actual projects to improve development efficiency. If you want to further learn the advanced usage of MyBatis, it is recommended to refer to the official documentation and related books for continuous in-depth study and practice. I wish you greater success in your MyBatis learning journey!
The above is the detailed content of Learn the MyBatis entry program: simply master the key skills. For more information, please follow other related articles on the PHP Chinese website!