mybatis框架入门案例

mybatis框架入门案例


今天学习了mybatis的简单的案例,感觉收获很大,写一个很简单的入门程序来快速的说明mybatis的用法

案例的需求

mybatis环境的搭建

1:导入相应的的架包(jar)和导入数据库的文件


导入相应的的架包(jar)
asm-3.3.1.jar
cglib-2.2.2.jar
commons-logging-1.1.1.jar 
javassost-3.17.1-GA.jar
junit-4.9.jar
log4j-1.2.17.jar
log4j-api-2.0-rc1.jar
log4j-core-2.0-rc1.jar
mybatis-3.2.7.jar
mysql-connector-java-5.1.7-bin.jar
slf4j-api-1.7.5.jar
slf4j-log4j12-1.7.5.jar


数据库表tb_person
CREATE TABLE tb_person(
   id INT PRIMARY KEY AUTO_INCREMENT,
   NAME VARCHAR(18),
   sex  VARCHAR(18),
   age INT
   );
INSERT INTO tb_person(NAME,sex,age) VALUES('jack','男',23)  

2:配置mybatis的配置文件

** mybatis-config.xml**








    
    
    
    
    
        
        
        
        
    
    


    //通过包扫描的形式加载配置文件
    


db.proprities

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatisonetoone?characterEncoding=utf-8
jdbc.username=root
jdbc.password=admin

** log4j.properties****

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

pojo类:

person类
public class Person implements Serializable{

private static final long serialVersionUID = 1L;
private Integer id; 
private String name;
private String sex;
private Integer age;

提供共有的getter()和setter()方法
...........

}

Person的映射文件PersonMapper.xml
PersonMapper.xml:








提供一个mapper接口PersonMapper.java

import com.mybatis.pojo.Person;

public interface PersonMapper {

    //按照id进行查询数据表,将其结果返回的结构是一个Person对象 
    public Person findPersonById(Integer id);

}   


测试类:MyTest.java
@Test
public void testfindPersonById() throws IOException {
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource );
    SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession openSession = factory.openSession();
    //获得mapper接口的对象
    PersonMapper mapper = openSession.getMapper(PersonMapper.class);
    Person person = mapper.findPersonById(1);
    System.out.println(person);
    openSession.commit();
}

控制台输出的结果:
DEBUG [main] - ==>  Preparing: select *from tb_person where id=? 
DEBUG [main] - ==> Parameters: 1(Integer)
DEBUG [main] - <==      Total: 1
Person [id=1, name=jack, sex=男, age=23]

小结:通过这个简答的mybatis的入门级别的小程序,使我可以迅速的对mybatis的工作原理有一个深入的理解,是我学习mybatis框架开始的第一步,我会继续深入的学习。如果遇到大牛路过,请各位大牛多多指点,本人小白一枚。

你可能感兴趣的:(mybatis)