文档章节

mybatis 一对一和一对多

小代码2016
 小代码2016
发布于 2016/03/13 19:26
字数 3194
阅读 413
收藏 8
点赞 1
评论 0

目录结构:


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为名,不然联合查询就只有一条数据



© 著作权归作者所有

共有 人打赏支持
小代码2016
粉丝 35
博文 311
码字总数 153495
作品 0
安阳
程序员
MyBatis学习总结(五)——实现关联表查询

一、一对一关联 1.1、提出需求   根据班级id查询班级信息(带老师的信息) 1.2、创建表和数据   创建一张教师表和班级表,这里我们假设一个老师只负责教一个班,那么老师和班级之间的关系就...

Carl_ ⋅ 2015/08/12 ⋅ 0

MyBatis学习总结(五)——实现关联表查询

一、一对一关联 1.1、提出需求   根据班级id查询班级信息(带老师的信息) 1.2、创建表和数据   创建一张教师表和班级表,这里我们假设一个老师只负责教一个班,那么老师和班级之间的关系就...

Carl_ ⋅ 2015/08/12 ⋅ 0

MyBatis 实践 -动态SQL/关联查询

标签: Java与存储 动态SQL 动态SQL提供了对SQL语句的灵活操作,通过表达式进行判断,对SQL进行拼接/组装. if 对查询条件进行判断,如果输入参数不为空才进行查询条件的拼接. mapper 会自动处理...

hanqing280441589 ⋅ 2016/02/28 ⋅ 0

Mybatis3.4.x技术内幕(二十一):参数设置、结果封装、级联查询、延迟加载原理分析

Mybatis在执行查询时,其参数设置、结果封装、级联查询、延迟加载,是最基本的功能和用法,我们有必要了解其工作原理,重点阐述级联查询和延迟加载。 1、MetaObject MetaObject用于反射创建对...

祖大俊 ⋅ 2016/09/16 ⋅ 0

mybatis02映射&动态sql&关联查询&spring整合mybatis

输入映射和输出映射: 动态sql: 关联查询_一对一: 关联查询_一对多: 一对一,一对多操作的区别: 一对一,resultMap里面关联另一个实体时用 association 一对多,resultMap里面关联另一个实体...

萧小蚁 ⋅ 2016/07/17 ⋅ 0

MyBatis之使用resultMap实现高级映射

对于数据库中对表的增删改查操作,我们知道增删改都涉及的是单表,而只有查询操作既可以设计到单表操作又可以涉及到多表操作,所以对于输入映射parameterType而言是没有所谓的高级映射的,也...

瑟青豆 ⋅ 06/20 ⋅ 0

mybatis(八)mapper映射文件配置之select、resultMap

上篇介绍了insert、update、delete的用法,本篇将介绍select、resultMap的用法。select无疑是我们最常用,也是最复杂的,mybatis通过resultMap能帮助我们很好地进行高级映射。下面就开始看看...

LCZ777 ⋅ 2014/12/19 ⋅ 0

【MyBatis框架】订单商品数据模型-分析思路

我们接下来要对即将用来实验的订单商品数据模型进行分析。 首先在MySql中创建mybatis数据库,在其中创建以下表: CREATE TABLE ( int(11) NOT NULL AUTO_INCREMENT, varchar(32) NOT NULL CO...

Mysoft ⋅ 2015/09/18 ⋅ 0

myBatis --关联查询

业务需求,需要查询到的结果集如下 结构分析 1.查询出所有的评论,即data[]里面是一个list 2.查出list中每个评论id(即userObjectCmmtId)下面所有的子评论,即一对多的关系。 实现方法如下 1....

求是科技 ⋅ 2015/10/21 ⋅ 0

SSH框架之MyBatis专题3:关联关系查询

1 关联查询 当查询内容涉及具有关联关系的多个表时,就需要使用关联关系查询。根据表与表之间的关联关系的不同,关联查询分为四种: 1、一对一关联查询; 2、一对多关联查询; 3、多对一关联...

糖醋白糖 ⋅ 04/06 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

JavaScript零基础入门——(十一)JavaScript的DOM操作

JavaScript零基础入门——(十一)JavaScript的DOM操作 大家好,欢迎回到我们的JavaScript零基础入门。最近有些同学问我说,我讲的的比书上的精简不少。其实呢,我主要讲的是我在开发中经常会...

JandenMa ⋅ 29分钟前 ⋅ 0

volatile和synchronized的区别

volatile和synchronized的区别 在讲这个之前需要先了解下JMM(Java memory Model :java内存模型):并发过程中如何处理可见性、原子性、有序性的问题--建立JMM模型 详情请看:https://baike.b...

MarinJ_Shao ⋅ 56分钟前 ⋅ 0

深入分析Kubernetes Critical Pod(一)

Author: xidianwangtao@gmail.com 摘要:大家在部署Kubernetes集群AddOn组件的时候,经常会看到Annotation scheduler.alpha.kubernetes.io/critical-pod"="",以表示这是一个关键服务,那你知...

WaltonWang ⋅ 今天 ⋅ 0

原子性 - synchronized关键词

原子性概念 原子性提供了程序的互斥操作,同一时刻只能有一个线程能对某块代码进行操作。 原子性的实现方式 在jdk中,原子性的实现方式主要分为: synchronized:关键词,它依赖于JVM,保证了同...

dotleo ⋅ 今天 ⋅ 0

【2018.06.22学习笔记】【linux高级知识 14.4-15.3】

14.4 exportfs命令 14.5 NFS客户端问题 15.1 FTP介绍 15.2/15.3 使用vsftpd搭建ftp

lgsxp ⋅ 今天 ⋅ 0

JeeSite 4.0 功能权限管理基础(Shiro)

Shiro是Apache的一个开源框架,是一个权限管理的框架,实现用户认证、用户授权等。 只要有用户参与一般都要有权限管理,权限管理实现对用户访问系统的控制,按照安全规则或者安全策略控制用户...

ThinkGem ⋅ 昨天 ⋅ 0

python f-string 字符串格式化

主要内容 从Python 3.6开始,f-string是格式化字符串的一种很好的新方法。与其他格式化方式相比,它们不仅更易读,更简洁,不易出错,而且速度更快! 在本文的最后,您将了解如何以及为什么今...

阿豪boy ⋅ 昨天 ⋅ 0

Python实现自动登录站点

如果我们想要实现自动登录,那么我们就需要能够驱动浏览器(比如谷歌浏览器)来实现操作,ChromeDriver 刚好能够帮助我们这一点(非谷歌浏览器的驱动有所不同)。 一、确认软件版本 首先我们...

blackfoxya ⋅ 昨天 ⋅ 0

线性回归原理和实现基本认识

一:介绍 定义:线性回归在假设特证满足线性关系,根据给定的训练数据训练一个模型,并用此模型进行预测。为了了解这个定义,我们先举个简单的例子;我们假设一个线性方程 Y=2x+1, x变量为商...

wangxuwei ⋅ 昨天 ⋅ 0

容器之查看minikue的environment——minikube的环境信息

执行如下命令 mjduan@mjduandeMacBook-Pro:~/Docker % minikube docker-envexport DOCKER_TLS_VERIFY="1"export DOCKER_HOST="tcp://192.168.99.100:2376"export DOCKER_CERT_PATH="/U......

汉斯-冯-拉特 ⋅ 昨天 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部