1. Configure mybatis-config.xml
Add configuration items
<configuration> <!-- It will be used when using the mapper, no configuration is required in the normal way--> <settings> <!-- changes from the defaults for testing --> <setting name="cacheEnabled" value="false" /> <setting name="useGeneratedKeys" value="true" /> <setting name="defaultExecutorType" value="REUSE" /> </settings> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <!-- Configure database connection information--> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="ok" /> </dataSource> </environment> </environments> <mappers> <mapper resource="com/cc/TestMyBaties/mapping/Student.xml"/> </mappers> </configuration>
2. Add mapper
public interface StudentMapper { void addStudent(Student student); // The method name should be the same as the corresponding xml Student selectStudentById(int id); }
Only need to write the interface, no need to implement the specific class, it will be directly mapped to the corresponding xml
3. Modify the XML
namespace needs to specify mapper
<mapper namespace="com.cc.TestMyBaties.dao.StudentMapper"> <!-- Example table returned --> <resultMap type="com.cc.TestMyBaties.entity.Student" id="resultListStus"> <id column="sid" property="sid" /> <id column="sname" property="sname" /> <id column="sex" property="sex" /> </resultMap> <select id="selectStudentById" parameterType="int" resultType="com.cc.TestMyBaties.entity.Student"> select * from Student where sid = #{id} </select> <select id="selectStudents" parameterType="int" resultMap="resultListStus"> select * from Student </select> <insert id="addStudent" parameterType="com.cc.TestMyBaties.entity.Student" useGeneratedKeys="true" keyProperty="sid"> insert into Student(sname,sex) values(#{sname},#{sex}) </insert> <update id="editStudent" parameterType="com.cc.TestMyBaties.entity.Student"> update Student set sname=#{sname},sex=#{sex} where sid=#{sid} </update> <delete id="delStudent" parameterType="int"> delete from Student where sid=#{sid} </delete> </mapper>
4. Modify the use method
public void insertStudent(){ SqlSession session = this.getSessionfactory().openSession(); StudentMapper mapper = session.getMapper(StudentMapper.class); // Just use the mapper directly Student stu = new Student(); stu.setSname("xiaoming"); stu.setSex("man"); mapper.addStudent(stu); session.commit(); } public static void main(String[] args){ StudentService service = new StudentService(); service.insertStudent(); }