mybatis(二)使用映射器进行开发

1.配置mybatis-config.xml

增加配置项

 <configuration>
	<!-- 使用映射器时会用到,普通方式无需配置 -->
	<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" />
       <!-- 配置数据库连接信息 -->
       <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.添加映射器

public interface StudentMapper {
	void addStudent(Student student); // 方法名要与相应的xml中一样
	
	Student selectStudentById(int id);
}

 只需要写接口,不需要具体实现类,他会直接映射到相应的xml

 

3.修改XML

 

namespace 需要指定映射器

<mapper namespace="com.cc.TestMyBaties.dao.StudentMapper">
	<!-- 所返回的例表 -->
	<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.修改掉用方法

	public void insertStudent(){
		SqlSession session = this.getSessionfactory().openSession();
		StudentMapper mapper = session.getMapper(StudentMapper.class); // 直接使用映射器即可
		
		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();

}

 

猜你喜欢

转载自llyilo.iteye.com/blog/2366599