mybatis 一对一和一对多
mybatis 一对一和一对多
小代码2016 发表于2年前
mybatis 一对一和一对多
  • 发表于 2年前
  • 阅读 379
  • 收藏 8
  • 点赞 1
  • 评论 0

标题:腾讯云 新注册用户域名抢购1元起>>>   

目录结构:


D:\code\smvc\mybatis-two>tree /f
卷 软件 的文件夹 PATH 列表
卷序列号为 0000-CD08
D:.
│  .classpath
│  .project
│  pom.xml
│
├─.settings
│      org.eclipse.core.resources.prefs
│      org.eclipse.jdt.core.prefs
│      org.eclipse.m2e.core.prefs
│
├─sql
│      create.sql
│
└─src
    ├─main
    │  ├─java
    │  │  └─com
    │  │      └─laolang
    │  │          ├─domain
    │  │          │      Address.java
    │  │          │      AddressMapper.xml
    │  │          │      Course.java
    │  │          │      CourseMapper.xml
    │  │          │      Person.java
    │  │          │      PersonMapper.xml
    │  │          │      Student.java
    │  │          │      StudentMapper.xml
    │  │          │      Tutor.java
    │  │          │      TutorMapper.xml
    │  │          │
    │  │          ├─mapper
    │  │          │      AddressMapper.java
    │  │          │      CourseMapper.java
    │  │          │      PersonMapper.java
    │  │          │      StudentMapper.java
    │  │          │      TutorMapper.java
    │  │          │
    │  │          ├─services
    │  │          │      AddressService.java
    │  │          │      CourseService.java
    │  │          │      PersonService.java
    │  │          │      StudentService.java
    │  │          │      TutorService.java
    │  │          │
    │  │          └─util
    │  │                  MybatisUtil.java
    │  │
    │  └─resources
    │      │  jdbc.properties
    │      │  mybatis-config.xml
    │      │
    │      └─com
    │          └─laolang
    │              └─domain
    │                      AddressMapper.xml
    │                      CourseMapper.xml
    │                      PersonMapper.xml
    │                      StudentMapper.xml
    │                      TutorMapper.xml
    │
    └─test
        ├─java
        │  └─com
        │      └─laolang
        │          └─services
        │                  AddressServiceTest.java
        │                  CourseServiceTest.java
        │                  PersonServiceTest.java
        │                  StudentServiceTest.java
        │                  TutorServiceTest.java
        │
        └─resources
            │  jdbc.properties
            │  mybatis-config.xml
            │
            └─com
                └─laolang
                    └─domain
                            AddressMapper.xml
                            CourseMapper.xml
                            PersonMapper.xml
                            StudentMapper.xml
                            TutorMapper.xml


D:\code\smvc\mybatis-two>

mybatis配置:


jdbc.properties


driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis_study
username=root
password=root


mybatis-config.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>

    <!-- 加载 jdbc properties 文件 -->
    <properties resource="jdbc.properties" />

    <typeAliases>
        <typeAlias alias="Student" type="com.laolang.domain.Student" />
        <typeAlias alias="Address" type="com.laolang.domain.Address" />
        <typeAlias alias="Person" type="com.laolang.domain.Person" />
        <typeAlias alias="Course" type="com.laolang.domain.Course" />
        <typeAlias alias="Tutor" type="com.laolang.domain.Tutor" />
    </typeAliases>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <dataSource type="POOLED">
                <property name="driver" value="${driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="com/laolang/domain/StudentMapper.xml" />
        <mapper resource="com/laolang/domain/AddressMapper.xml" />
        <mapper resource="com/laolang/domain/PersonMapper.xml" />
        <mapper resource="com/laolang/domain/CourseMapper.xml" />
        <mapper resource="com/laolang/domain/TutorMapper.xml" />
    </mappers>
</configuration>


实体类和Mapper.xml映射文件:


com.laolang.domain.Student


package com.laolang.domain;

public class Student {

	public Student() {
		super();
	}

	public Student(String name, int age, String sex) {
		super();
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	public Student(int id, String name, int age, String sex) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.sex = sex;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age
				+ ", sex=" + sex + "]";
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	private int id;
	private String name;
	private int age;
	private String sex;
}


com.laolang.domain.domain.StudentMapper.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.laolang.mapper.StudentMapper">
	<resultMap type="Student" id="StudentResult">
		<id property="id" column="id"/>
		<result property="name" column="name"/>
		<result property="age" column="age"/>
		<result property="sex" column="sex"/>
	</resultMap>
	
	<select id="selectAll" resultMap="StudentResult">
		select id,name,age,sex from student
	</select>
	
	<select id="selectById" parameterType="int" resultType="Student">
		select id,name,age,sex from student where id = #{id} 
	</select>
	
	<select id="selectByName" parameterType="String" resultType="Student">
		select id,name,age,sex from student where name = #{name}
	</select>
	
	<insert id="insertStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="id">
		insert into student ( name, age, sex ) values(#{name},#{age},#{sex})
	</insert>
	
	<update id="updateStudent" parameterType="Student">
		update student set name = #{name} , age = #{age} , sex = #{age}
		where id = #{id}
	</update>
	
	<delete id="deleteStudentById" parameterType="int">
		delete from student where id = #{id}
	</delete>
	
</mapper>


com.laolang.domain.Address



package com.laolang.domain;

public class Address {

	public Address() {
		super();
	}

	public Address(String street, String city, String zip) {
		super();
		this.street = street;
		this.city = city;
		this.zip = zip;
	}

	public Address(int id, String street, String city, String zip) {
		super();
		this.id = id;
		this.street = street;
		this.city = city;
		this.zip = zip;
	}

	@Override
	public String toString() {
		return "Address [id=" + id + ", street=" + street + ", city=" + city
				+ ", zip=" + zip + "]";
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getZip() {
		return zip;
	}

	public void setZip(String zip) {
		this.zip = zip;
	}

	private int id;
	private String street;
	private String city;
	private String zip;
}


com.laolang.domain.AddressMapper.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.laolang.mapper.AddressMapper">

	<resultMap type="Address" id="AddressResult">
		<id property="id" column="addr_id" />
		<result property="street" column="addr_street" />
		<result property="city" column="addr_city" />
		<result property="zip" column="addr_zip" />
	</resultMap>

	<select id="findAddresssById" parameterType="int" resultType="Address">
		select
		id,street,city,zip from address where
		id = #{id}
	</select>
</mapper>


com.laolang.domain.Person



package com.laolang.domain;

public class Person {

	public Person() {
		super();
	}

	public Person(String name, String email, String phone, Address address) {
		super();
		this.name = name;
		this.email = email;
		this.phone = phone;
		this.address = address;
	}

	public Person(int id, String name, String email, String phone,
			Address address) {
		super();
		this.id = id;
		this.name = name;
		this.email = email;
		this.phone = phone;
		this.address = address;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", email=" + email
				+ ", phone=" + phone +  "]";
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public Address getAddresss() {
		return address;
	}

	public void setAddresss(Address addresss) {
		this.address = addresss;
	}

	private int id;
	private String name;
	private String email;
	private String phone;
	private Address address;
}


com.laolang.domain.PersonMapper.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.laolang.mapper.PersonMapper">
	<resultMap type="Address" id="AddressResult">
		<id property="id" column="id" />
		<result property="street" column="street" />
		<result property="city" column="city" />
		<result property="zip" column="zip" />
	</resultMap>

	<resultMap type="Person" id="PersonWithAddressResult">
		<id property="id" column="id" />
		<result property="name" column="name" />
		<result property="email" column="email" />
		<result property="phone" column="phone" />
		<association property="address" column="addr_id"
			select="com.laolang.mapper.AddressMapper.findAddresssById" />
	</resultMap>



	<select id="findPersonWithAddress" parameterType="int"
		resultMap="PersonWithAddressResult">
		select id,name,email,phone,addr_id from person where id = #{id}
	</select>

	<select id="findPersonById" parameterType="int" resultType="Person">
		select id,name,email,phone from person where id = #{id}
	</select>



</mapper>

com.laolang.domain.Tutor


package com.laolang.domain;

import java.util.List;

public class Tutor {

	public Tutor() {
		super();
	}

	public Tutor(String name, String email, String phone, Address address,
			List<Course> courses) {
		super();
		this.name = name;
		this.email = email;
		this.phone = phone;
		this.address = address;
		this.courses = courses;
	}

	public Tutor(int id, String name, String email, String phone,
			Address address, List<Course> courses) {
		super();
		this.id = id;
		this.name = name;
		this.email = email;
		this.phone = phone;
		this.address = address;
		this.courses = courses;
	}

	@Override
	public String toString() {
		return "Tutor [id=" + id + ", name=" + name + ", email=" + email
				+ ", phone=" + phone +  "]";
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}

	public Address getAddress() {
		return address;
	}

	public void setAddress(Address address) {
		this.address = address;
	}

	public List<Course> getCourses() {
		return courses;
	}

	public void setCourses(List<Course> courses) {
		this.courses = courses;
	}

	private int id;
	private String name;
	private String email;
	private String phone;
	private Address address;
	private List<Course> courses;
}

com.laolang.domain.TutorMapper.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.laolang.mapper.TutorMapper">
    <resultMap type="Address" id="AddressResult">
        <id property="id" column="id" />
        <result property="street" column="street" />
        <result property="city" column="city" />
        <result property="zip" column="zip" />
    </resultMap>

    <resultMap type="Course" id="CourseResult">
        <id property="id" column="cid" />
        <result property="name" column="cname" />
        <result property="description" column="description" />
        <result property="startDate" column="start_date" jdbcType="DATE" javaType="java.util.Date"/>
        <result property="endDate" column="end_date"   jdbcType="DATE" javaType="java.util.Date"/>
        <result property="tutorId" column="tutor_id"   />
    </resultMap>

    <resultMap type="Tutor" id="TutorResult">
        <id property="id" column="tid" />
        <result property="name" column="tname" />
        <result property="email" column="email" />
        <result property="phone" column="phone" />
        <collection property="courses" resultMap="CourseResult" />
    </resultMap>




    <select id="findTutorWithCourseById" parameterType="int"
        resultMap="TutorResult">
        select t.tid,t.tname,email,phone,c.cid,c.cname,c.description,start_date,end_date
        from tutor t left outer join course c on
        t.tid = c.tutor_id
        where t.tid = #{id};
    </select>



</mapper>




com.laolang.domain.Course



package com.laolang.domain;

import java.util.Date;

public class Course {

	public Course() {
		super();
	}

	public Course(String name, String desc, Date startDate, Date endDate,
			int tutorId) {
		super();
		this.name = name;
		this.description = desc;
		this.startDate = startDate;
		this.endDate = endDate;
		this.tutorId = tutorId;
	}

	public Course(int id, String name, String description, Date startDate,
			Date endDate, int tutorId) {
		super();
		this.id = id;
		this.name = name;
		this.description = description;
		this.startDate = startDate;
		this.endDate = endDate;
		this.tutorId = tutorId;
	}

	@Override
	public String toString() {
		return "Course [id=" + id + ", name=" + name + ", description=" + description
				+ ", startDate=" + startDate + ", endDate=" + endDate
				+ ", tutorId=" + tutorId + "]";
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDesc() {
		return description;
	}

	public void setDesc(String desc) {
		this.description = desc;
	}

	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public int getTutorId() {
		return tutorId;
	}

	public void setTutorId(int tutorId) {
		this.tutorId = tutorId;
	}

	private int id;
	private String name;
	private String description;
	private Date startDate;
	private Date endDate;
	private int tutorId;
}

com.laolang.domain.CourseMappeer.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.laolang.mapper.CourseMapper">
    <resultMap type="Course" id="CourseResult">
        <id property="id" column="cid" />
        <result property="name" column="cname" />
        <result property="description" column="description" />
        <result property="startDate" column="start_date" jdbcType="DATE" javaType="java.util.Date"/>
        <result property="endDate" column="end_date"   jdbcType="DATE" javaType="java.util.Date"/>
        <result property="tutorId" column="tutor_id"   />
    </resultMap>
    
    <select id="findCourseById" parameterType="int" resultMap="CourseResult">
        select cid,cname,description,start_date,end_date,tutor_id from course where cid = #{id};
    </select>
</mapper>




Mapper接口


com.laolang.mapper.StudentMapper


package com.laolang.mapper;

import java.util.List;

import com.laolang.domain.Student;

public interface StudentMapper {

	public List<Student> selectAll();

	public Student selectById(int id);

	public Student selectByName(String name);
	
	public void insertStudent(Student student );
	
	public void updateStudent(Student student );
	
	public void deleteStudentById(int id );
}


com.laolang.mapper.AddressMapper



package com.laolang.mapper;

import com.laolang.domain.Address;

public interface AddressMapper {

	public Address findAddresssById( int id );
}


com.laolang.mapper.PersonMapper



package com.laolang.mapper;

import com.laolang.domain.Person;

public interface PersonMapper {

	public Person findPersonWithAddress( int id);
	
	public Person findPersonById( int id );
}

com.laolang.mapper.TutorMapper


package com.laolang.mapper;

import com.laolang.domain.Tutor;

public interface TutorMapper {
	public Tutor findTutorWithCourseById( int id );
	
}


com.laolang.mapper.CourseMapper



package com.laolang.mapper;

import com.laolang.domain.Course;

public interface CourseMapper {
	
	public Course findCourseById( int id );

}




service层


com.laolang.services.StudentService


package com.laolang.services;

import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.laolang.domain.Student;
import com.laolang.mapper.StudentMapper;
import com.laolang.util.MybatisUtil;

public class StudentService {

	public List<Student> selectAll() {
		SqlSession session = MybatisUtil.openSession();

		try {
			StudentMapper studentMapper = session
					.getMapper(StudentMapper.class);
			return studentMapper.selectAll();
		} finally {
			session.close();
		}
	}

	public Student selectById(int id) {
		SqlSession session = MybatisUtil.openSession();

		try {
			StudentMapper studentMapper = session
					.getMapper(StudentMapper.class);
			return studentMapper.selectById(id);
		} finally {
			session.close();
		}
	}

	public Student selectByName(String name) {
		SqlSession session = MybatisUtil.openSession();

		try {
			StudentMapper studentMapper = session
					.getMapper(StudentMapper.class);
			return studentMapper.selectByName(name);
		} finally {
			session.close();
		}
	}

	public void insertStudent(Student stu) {
		SqlSession session = MybatisUtil.openSession();

		try {
			StudentMapper studentMapper = session
					.getMapper(StudentMapper.class);
			studentMapper.insertStudent(stu);
			session.commit();
		} finally {
			session.close();
		}
	}

	public void updateStudent(Student student) {
		SqlSession session = MybatisUtil.openSession();

		try {
			StudentMapper studentMapper = session
					.getMapper(StudentMapper.class);
			studentMapper.updateStudent(student);
			session.commit();
		} finally {
			session.close();
		}
	}

	public void deleteStudentById(int id) {
		SqlSession session = MybatisUtil.openSession();

		try {
			StudentMapper studentMapper = session
					.getMapper(StudentMapper.class);
			studentMapper.deleteStudentById(id);
			session.commit();
		} finally {
			session.close();
		}
	}

}


com.laolang.services.AddressService




package com.laolang.services;

import org.apache.ibatis.session.SqlSession;

import com.laolang.domain.Address;
import com.laolang.mapper.AddressMapper;
import com.laolang.util.MybatisUtil;

public class AddressService {

	
	public Address findAddresssById( int id ){
		SqlSession session = MybatisUtil.openSession();

		try {
			AddressMapper addressMapper = session
					.getMapper(AddressMapper.class);
			Address address =  addressMapper.findAddresssById(id);
			if( address == null ){
				System.out.println("未查询到address!!!");
			}
			return address;
		} finally {
			session.close();
		}
	}
}


com.laolang.services.PersonService



package com.laolang.services;

import org.apache.ibatis.session.SqlSession;

import com.laolang.domain.Person;
import com.laolang.mapper.PersonMapper;
import com.laolang.util.MybatisUtil;

public class PersonService {

	public Person findPersonWithAddress( int id ){
		SqlSession session = MybatisUtil.openSession();

		try {
			PersonMapper personMapper = session
					.getMapper(PersonMapper.class);
			return personMapper.findPersonWithAddress(id);
		} finally {
			session.close();
		}
	}
	
	public Person findPersonById( int id ){
		SqlSession session = MybatisUtil.openSession();

		try {
			PersonMapper personMapper = session
					.getMapper(PersonMapper.class);
			return personMapper.findPersonById(id);
		} finally {
			session.close();
		}
	}
}

com.laolang.service.TutorService


package com.laolang.services;

import org.apache.ibatis.session.SqlSession;

import com.laolang.domain.Tutor;
import com.laolang.mapper.TutorMapper;
import com.laolang.util.MybatisUtil;

public class TutorService {
	public Tutor findTutorWithCourseById( int id ){
		SqlSession session = MybatisUtil.openSession();

		try {
			TutorMapper tutorMapper = session
					.getMapper(TutorMapper.class);
			return tutorMapper.findTutorWithCourseById(id);
		} finally {
			session.close();
		}
	}
}


com.laolang.services.CourseService



package com.laolang.services;

import org.apache.ibatis.session.SqlSession;

import com.laolang.domain.Course;
import com.laolang.mapper.CourseMapper;
import com.laolang.util.MybatisUtil;

public class CourseService {

	public Course findCourseById( int id ){
		SqlSession session = MybatisUtil.openSession();

		try {
			CourseMapper courseMapper = session
					.getMapper(CourseMapper.class);
			return courseMapper.findCourseById(id);
		} finally {
			session.close();
		}
	}
}




mybatis工具类


com.laolang.util.MybatisUtil


package com.laolang.util;

import java.io.IOException;
import java.io.InputStream;

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

public class MybatisUtil {

	
	
	public static SqlSessionFactory getSqlSessionFactory(){
		if( null == sqlSessionFactory ){
			
			try {
				InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return sqlSessionFactory;
	}
	
	public static SqlSession openSession(){
		return getSqlSessionFactory().openSession();
	}
	
	private static SqlSessionFactory sqlSessionFactory;
}


测试类:


StudentServiceTest


package com.laolang.services;

import java.util.List;

import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import com.laolang.domain.Student;

public class StudentServiceTest {

    @BeforeClass
    public static void setUp() {
        studentService = new StudentService();
    }

//    @Ignore
    @Test
    public void testSelectAll() {
        System.out.println("-->查询所有-----------");
        List<Student> students = studentService.selectAll();
        for (Student stu : students) {
            System.out.println(stu);
        }
        System.out.println("---------------------------\n\n");
    }

//    @Ignore
    @Test
    public void testSelectById() {
        System.out.println("-->通过 id 查询-----------");
        Student stu = studentService.selectById(1);
        System.out.println(stu);
        System.out.println("---------------------------\n\n");
    }

    @Ignore
    @Test
    public void testSelectByName() {
        System.out.println("-->通过 name 查询-----------");
        Student stu = studentService.selectByName("小代码");
        System.out.println(stu);
        System.out.println("---------------------------\n\n");
    }

    @Ignore
    @Test
    public void testInsertStudent() {
        System.out.println("-->插入-----------");
        String name = "天涯";
        Student stu = new Student(name, 34, "男");
        studentService.insertStudent(stu);
        stu = studentService.selectByName(name);
        System.out.println(stu);
        System.out.println("---------------------------\n\n");
    }

    @Ignore
    @Test
    public void testUpdateStudent() {
        System.out.println("-->修改-----------");
        Student stu = studentService.selectById(1);
        System.out.println();
        stu.setName("xiaodaima");
        studentService.updateStudent(stu);
        stu = studentService.selectById(1);
        System.out.println(stu);
        System.out.println("---------------------------\n\n");
    }

    @Ignore
    @Test
    public void testDeleteStudentById() {
        System.out.println("-->删除-----------");
        List<Student> studentList = studentService.selectAll();
        for( Student stu : studentList ){
            System.out.println(stu);
        }
        studentService.deleteStudentById(7);
        System.out.println("删除后:\n");
        studentList = studentService.selectAll();
        for( Student stu : studentList ){
            System.out.println(stu);
        }
        System.out.println("---------------------------\n\n");
        
    }

    private static StudentService studentService;
}


com.laolang.services.AddressTest



package com.laolang.services;

import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import com.laolang.domain.Address;

public class AddressServiceTest {

    
    @BeforeClass
    public static void setUp(){
        addressService = new AddressService();
    }
    
//    @Ignore
    @Test
    public void testFindAddressById(){
        System.out.println("-->通过ID查询地址------");
        Address address = addressService.findAddresssById(1);
        System.out.println(address.toString());
        System.out.println("---------------------\n\n");
        
    }
    
    private static AddressService addressService;
}


com.laolang.services.PersonServiceTest



package com.laolang.services;

import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import com.laolang.domain.Address;
import com.laolang.domain.Person;
import com.laolang.services.PersonService;

public class PersonServiceTest {

    
    @BeforeClass
    public static void setUp(){
        personService = new PersonService();
    }
    
//    @Ignore
    @Test
    public void testFindPersonWithAddress(){
        System.out.println("-->查询带地址的信息-----------");
        Person p = personService.findPersonWithAddress(1);
        Address a = p.getAddresss();
        System.out.println("Person:"+p.toString()+" Address:" + a.toString());
        System.out.println("-------------------------");
    }
    
//    @Ignore
    @Test
    public void testFindPersonById(){
        System.out.println("-->查询信息-----------");
        Person p = personService.findPersonById(1);
        System.out.println("Person:"+p.toString());
        System.out.println("-------------------------");
    }
    
    
    
    private static PersonService personService;
}

CourseServiceTest


package com.laolang.services;

import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import com.laolang.domain.Course;

public class CourseServiceTest {

	@BeforeClass
	public static void setUp(){
		courseService = new CourseService();
	}
	
//	@Ignore
	@Test
	public void testFindCourseById(){
		System.out.println("-->根据ID查询课程信息---------");
		Course course = courseService.findCourseById(3);
		System.out.println(course);
		
		System.out.println("-------------------------");
	}
	
	private static CourseService courseService;
}


TourseServiceTest



package com.laolang.services;

import java.util.List;

import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import com.laolang.domain.Course;
import com.laolang.domain.Tutor;


public class TutorServiceTest {

	
	@BeforeClass
	public static void setUp(){
		tutorService = new TutorService();
	}
	
//	@Ignore
	@Test
	public void testFindTutorWithCourseById(){
		System.out.println("-->通过ID某教师所讲的课程------");
		Tutor tutor = tutorService.findTutorWithCourseById(1);
		List<Course> courses = tutor.getCourses();
		for( Course c : courses ){
			System.out.println(tutor.toString() + c.toString());
		}
		System.out.println("---------------------\n\n");
	}
	
	private static TutorService tutorService;
}






pom.xml



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.laolang.mybatis-study</groupId>
  <artifactId>mybatis-two</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>mybatis-two</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.6</version>
		</dependency>

		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>3.2.2</version>
		</dependency>

	</dependencies>
</project>


测试结果:



D:\code\smvc\mybatis-two>mvn test
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building mybatis-two 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:resources (default-resources) @ mybatis-two ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 7 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ mybatis-two ---
[INFO] Compiling 16 source files to D:\code\smvc\mybatis-two\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.4.3:testResources (default-testResources) @ mybatis-two ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 7 resources
[INFO]
[INFO] --- maven-compiler-plugin:2.3.2:testCompile (default-testCompile) @ mybatis-two ---
[INFO] Compiling 5 source files to D:\code\smvc\mybatis-two\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.7.2:test (default-test) @ mybatis-two ---
[INFO] Surefire report directory: D:\code\smvc\mybatis-two\target\surefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.laolang.services.AddressServiceTest
-->通过ID查询地址------
Address [id=1, street=长安街, city=洛阳, zip=123456]
---------------------


Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.867 sec
Running com.laolang.services.CourseServiceTest
-->根据ID查询课程信息---------
Course [id=3, name=linux, description=linux开发, startDate=Sun Jan 03 00:00:00 CST 2010, endDate=Fri Dec 03 00:00:00 CST 2010, tutorId=2]
-------------------------
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.023 sec
Running com.laolang.services.PersonServiceTest
-->查询信息-----------
Person:Person [id=1, name=长生, email=cs@gj.com, phone=13318188181]
-------------------------
-->查询带地址的信息-----------
Person:Person [id=1, name=长生, email=cs@gj.com, phone=13318188181] Address:Address [id=1, street=长安街, city=洛阳, zip=123456]
-------------------------
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.017 sec
Running com.laolang.services.StudentServiceTest
-->查询所有-----------
Student [id=1, name=xiaodaima, age=23, sex=23]
Student [id=2, name=laolang, age=23, sex=男]
Student [id=3, name=老狼, age=33, sex=男]
Student [id=4, name=行者, age=26, sex=男]
Student [id=5, name=tianya, age=34, sex=man]]
---------------------------


-->通过 id 查询-----------
Student [id=1, name=xiaodaima, age=23, sex=23]
---------------------------


Tests run: 6, Failures: 0, Errors: 0, Skipped: 4, Time elapsed: 0.018 sec
Running com.laolang.services.TutorServiceTest
-->通过ID某教师所讲的课程------
Tutor [id=1, name=陈老师, email=c@t.com, phone=12345677654]Course [id=1, name=javase, description=javase开发, startDate=Sun Jan 03 00:00:00 CST 2010, endDate=Fri Dec 03 00:00:00 CST 2010, tutorId=0]
Tutor [id=1, name=陈老师, email=c@t.com, phone=12345677654]Course [id=4, name=php, description=php开发, startDate=Sun Jan 03 00:00:00 CST 2010, endDate=Fri Dec 03 00:00:00 CST 2010, tutorId=0]
Tutor [id=1, name=陈老师, email=c@t.com, phone=12345677654]Course [id=7, name=vb.net, description=vb.net开发, startDate=Sun Jan 03 00:00:00 CST 2010, endDate=Fri Dec 03 00:00:00 CST 2010, tutorId=0]
Tutor [id=1, name=陈老师, email=c@t.com, phone=12345677654]Course [id=9, name=delphi, description=delphi开发, startDate=Sun Jan 03 00:00:00 CST 2010, endDate=Fri Dec 03 00:00:00 CST 2010, tutorId=0]
---------------------


Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.024 sec

Results :

Tests run: 11, Failures: 0, Errors: 0, Skipped: 4

[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 4.292s
[INFO] Finished at: Mon Mar 14 09:59:35 CST 2016
[INFO] Final Memory: 6M/14M
[INFO] ------------------------------------------------------------------------
D:\code\smvc\mybatis-two>


需要注意的点:

1、xml配置文件不能写错,不然会有各种资源找不到的错误

2、数据库中不能有名字相同的列,不然的话,联合查询的时候会出问题

3、ID字段绝对不能只以ID为名,不然联合查询就只有一条数据



共有 人打赏支持
粉丝 34
博文 311
码字总数 153495
×
小代码2016
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: