MyBatis

来源:互联网 发布:网络大电影编剧收费 编辑:程序博客网 时间:2024/06/06 03:46

20171130  daobao

———————————————————————————————————————————————————————— 

 实体类:

package com.atguigu.mybatis.bean;


public class Employee {
private Integer id;
private String lastName;
private String email;
private String  gender;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public String toString() {
return "Employee [id=" + id + ", lastName=" + lastName + ", email=" + email + ", gender=" + gender + "]";
}



}

//测试类

package com.atguigu.mybatis.test;


import java.io.IOException;
import java.io.Reader;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;


import com.atguigu.mybatis.bean.Employee;


public class MyBatisTest {


@Test
//1 xml配置文件
public void test() throws IOException {
// fail("Not yet implemented");
String resource = "mybatis-config.xml";
Reader reader = Resources.getResourceAsReader(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession openSession = sqlSessionFactory.openSession();
try {
Employee employee =openSession.selectOne("com.atguigu.mybatis.EmployeeMapper.selectEmp",1);
System.out.println("获取到的数据是:"+employee);
}finally {
openSession.close();
}
}


}

//xml主文件

<?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="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/mysql"/>
<property name="username" value="root" />
<property name="password" value="x5" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="EmployeeMapper.xml"/>
</mappers>
</configuration>

//映射文件

<?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.atguigu.mybatis.EmployeeMapper"><!--名称空间  -->
<select id="selectEmp"   resultType="com.atguigu.mybatis.bean.Employee">
select  id, last_name lastName,email,gender from tal_employy where id = #{id}
</select>
</mapper>


//记得自爆