mybatis编写顺序和内容
第一步,新建maven项目
省略......
第二步,下载pom依赖,添加内容如下:
注意,如过想用lombok插件,光导入pom还不行,还需要再idea中下载plugin插件
<dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.22</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.16</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> </dependencies>
第三步,新建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="mysql"> <environment id="mysql"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://134.175.xxx.xxx:3306/testdb"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/test01/dao/UserDao.xml"/> </mappers> </configuration>
第四步,编写数据库表的实体类,内容如下:
我这里用了lombok,所以没有写get,set方法
package com.test01.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private Integer id; private String name; private Integer age; }
第五步,编写dao映射接口
package com.test01.dao; import com.test01.domain.User; import java.util.List; public interface UserDao { public List<User> findAll(); public void insertData(User user); public void delData(User user); public void updateData(User user); public User findById(Integer id); }
第六步,编写dao的xml映射文件
<?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.test01.dao.UserDao"> <select id="findAll" resultType="com.test01.domain.User"> select * from user; </select> <insert id="insertData" parameterType="com.test01.domain.User"> insert into user (id, name, age) values (#{id},#{name},#{age}); </insert> <delete id="delData" parameterType="com.test01.domain.User"> delete from user where id=#{id} </delete> <update id="updateData" parameterType="com.test01.domain.User"> update user set name=#{name} where id=#{id} </update> <select id="findById" parameterType="Integer" resultType="com.test01.domain.User"> select * from user where id=#{id} </select> </mapper>
最后目录结构如下: