MyBatis案例一:入门

MyBatis案例一:入门

创建maven项目

  1. 使用maven project向导创建一个maven项目(不使用骨架,package使用:jar)
  2. 配置依赖包:
<dependencies>
  	
	<dependency>
		<groupId>junitgroupId>
		<artifactId>junitartifactId>
		<version>4.12version>
	dependency>
	
	<dependency>
		<groupId>org.mybatisgroupId>
		<artifactId>mybatisartifactId>
		<version>3.2.6version>
	dependency>
	
	<dependency>
	    <groupId>mysqlgroupId>
	    <artifactId>mysql-connector-javaartifactId>
	    <version>5.1.6version>
	dependency>		
  dependencies>
  1. 配置构建插件
<build>
		<plugins>
			
			<plugin>
				<groupId>org.apache.maven.pluginsgroupId>
				<artifactId>maven-resources-pluginartifactId>
				<version>2.7version>
				<configuration>
					<encoding>UTF-8encoding>
				configuration>
			plugin>
			
			<plugin>
				<groupId>org.apache.maven.pluginsgroupId>
				<artifactId>maven-compiler-pluginartifactId>
				<version>3.2version>
				<configuration>
					<source>1.7source>
					<target>1.7target>
					<encoding>UTF-8encoding>
				configuration>
			plugin>				
		plugins>
	build>

配置SqlMapConfig.xml

  1. 在src/main/java下创建mybatis配置文件SqlMapConfig.xml
  2. 添加dtd约束

	
  1. 配置环境,连接数据库
<configuration>
		<environments default="mysql">
			<environment id="mysql">
				<transactionManager type="jdbc">transactionManager>
				<dataSource type="pooled">
					<property name="url" value="jdbc:mysql://localhost:3306/hr"/>
					<property name="driver" value="com.mysql.jdbc.Driver"/>
					<property name="username" value="root"/>
					<property name="password" value="root"/>
				dataSource>
			environment>
		environments>
	configuration>

使用MyBatis

  1. 创建com.yy.mapper包、com.yy.domain包(添加实体类Dept)
  2. 创建DeptMapper接口文件,添加方法:
public List<Dept> getAll();

3.使用mybatis向导,创建DeptMapper.xml文件


	
	<mapper namespace="com.yy.mapper.DeptMapper">
	mapper>
  1. 添加查询statement
<select id="getAll" parameterType="com.yy.domain.Dept">
		select * from dept
select>
  1. 在DeptMapper.java文件上右键,使用junit向导,创建单元测试
public class DeptMapperTest {
     
		@Test
		public void testGetAll() {
     
			
		}
	}
  1. 编写测试方法代码
@Test
	public void testGetAll() throws IOException {
     
		InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);		
		SqlSession session = factory.openSession();
		DeptMapper deptMapper = session.getMapper(DeptMapper.class);
		session.close();
	}
  1. 在SqlMapConfig文件中添加映射文件
<mappers>
	<mapper resource="com/yy/mapper/DeptMapper.xml" />
mappers>
  1. 运行测试(项目右键=》run as=》Maven test),查看控制台显示信息

  2. 在DeptMapperTest.java文件上右键,直接运行junit Test也可以测试

你可能感兴趣的:(MyBatis,MyBatis,Maven,MySql)