MyBatis之入门程序

    刚学习MyBatis,写个入门从程序作为练习,依照从后往前的顺序来编写该入门程序。

 1.数据准备部分

1.1 数据库数据准备              

CREATE TABLE t_user 
(id primary key auto_increment, 
 username varchar(20) not null,
 password varchar(20) not null,
 email varchar(100) not null  
  )

INSERT INTO t_user VALUES(NULL,'Tom','123456','[email protected]');
INSERT INTO t_user VALUES(NULL,'maty','npartner','[email protected]');

1.2 该表对应的JavaBean

package com.maty.bean;

/**
 * @author maty e-mail:[email protected]
 * @version 创建时间:2018年6月21日 下午1:49:24 类说明
 */
public class User
{
	public Integer id;
	public String username;
	public String password;
	public String email;

	public Integer getId()
	{
		return id;
	}

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

	public String getUsername()
	{
		return username;
	}

	public void setUsername(String username)
	{
		this.username = username;
	}

	public String getPassword()
	{
		return password;
	}

	public void setPassword(String password)
	{
		this.password = password;
	}

	public String getEmail()
	{
		return email;
	}

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

	@Override
	public String toString()
	{
		return "User [id=" + id + ", username=" + username + ", password=" + password + ", email=" + email + "]";
	}
}

2.内容编写

2.1 编写Dao层的接口

UserMapper接口

package com.maty.mapper;

import com.maty.bean.User;

/** 
* @author maty  e-mail:[email protected]
* @version 创建时间:2018年6月21日 下午1:51:52 
* 类说明 
*/
public interface UserMapper
{
	public User getUserById(int id);
}

2.2 编写Dao层接口对应的sql的映射xml

sqlUserMapper




  

2.3 编写MySql数据库的配置文件

mysql_config.properties

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

2.4 编写MyBatis核心配置文件

mybatis-config.xml




	
	
		
			
			
				
				
				
				
			
		
	
	
		
	

3.测试类编写

MyTest类

package com.maty.test;

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;
import org.junit.Test;

import com.maty.bean.User;
import com.maty.mapper.UserMapper;

/** 
* @author maty  e-mail:[email protected]
* @version 创建时间:2018年6月21日 下午2:17:28 
* 类说明 
*/
public class MyTest
{
	@Test
	public void test01() throws Exception
	{
		InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
		SqlSession session = factory.openSession();
		UserMapper mapper = session.getMapper(UserMapper.class);
		User user = mapper.getUserById(1);
		System.out.println(user);
	}
}

测试结果:

User [id=1, username=Tom, password=123456, [email protected]]

    


        

        

    

你可能感兴趣的:(J2EE)