MyBatis使用(二)注解方式

直接上代码

1. SqlMapConfig.xml

  
  

	
		

	  
      
        
        
    
	
	
		
			
			
				  
                  
                  
                 
			
		
	
	
	
		
		
	
	

2. db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/zhjsdb?characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root

3. 新建一个包存放接口


@Select、@Delete  ...

package com.jx.annocation;

import org.apache.ibatis.annotations.Select;

import com.jx.pojo.Order;

public interface OrderMapper {
	
	@Select("Select * from tbl_order where id = #{id}")
	public Order getOrderById(int id);
}

编写测试类

package com.jx.sx;

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.jx.annocation.OrderMapper;
import com.jx.pojo.Order;

public class TestOrder {
	
	public SqlSessionFactory getSqlSessionFactory() throws IOException{
		//myBatis 配置文件
		String source = "SqlMapConfig.xml";
		//得到配置文件流
		InputStream inputStream = Resources.getResourceAsStream(source);
		
		SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream);
		
		inputStream.close();
		return factory;
	}
	
	@Test
	public void findUserByIdTest() throws IOException { 
		SqlSession session = this.getSqlSessionFactory().openSession();
		
		OrderMapper mapper = session.getMapper(OrderMapper.class);
		Order order = mapper.getOrderById(1);
		System.out.println(order);
		
		session.close();
	}
}

你可能感兴趣的:(MyBatis)