Mybatis执行流程
执行流程
环境的搭建(如何使用)
1.导入jar包
2.mybatis-conf.xml 放在src下面
<?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>
<typeAliases>
<typeAlias type="com.ujiuye.bean.PersonBean"
alias="person"/>
</typeAliases>
<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="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/ujiuye/mapper/PersonMapper.xml"></mapper>
</mappers>
</configuration>
3、写接口
public interface PersonDao {
/**获取所有的人
* @return
*/
List<PersonBean> getAll();
/**添加
* @param p
* @return
*/
int addPerson(PersonBean p);
/**根据主键删除
* @param pid
* @return
*/
int del(int pid);
/**修改
* @param p
* @return
*/
int updatePerson(PersonBean p);
}
4、写mapper 相当于dao接口的实现类
<?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.ujiuye.dao.PersonDao">
<select id="getAll" resultType="person" >
select *from person
</select>
<insert id="addPerson" parameterType="person">
insert person(pname,address)values(#{pname},#{address})
</insert>
<delete id="del" parameterType="int">
delete from person where pid=#{0}
</delete>
<update id="updatePerson" parameterType="person">
update person set pname=#{pname},address=#{address} where pid=#{pid}
</update>
</mapper>
5、测试类
public class MyTest {
@Test
public void test1() throws IOException {
//1.读取配置文件
InputStream is= Resources.getResourceAsStream("mybaits-conf.xml");
//2.获取SqlSessionFactory
SqlSessionFactory ssf=new SqlSessionFactoryBuilder().build(is);
//3.获取sqlsession
SqlSession session=ssf.openSession();
PersonDao dao = session.getMapper(PersonDao.class);
/* List<PersonBean> all = dao.getAll();
System.out.println(all);*/
/* PersonBean p1=new PersonBean(0,"rose","深圳");
int i = dao.addPerson(p1);
System.out.println("影响了"+i);*/
/*int i=dao.del(5);
System.out.println("影响了"+i);*/
PersonBean p1=new PersonBean(6,"tomcat","纽约");
int i = dao.updatePerson(p1);
System.out.println("影响了"+i);
session.commit();
session.close();
}}