执行原理
入门程序编写
1.pom.xml 文件
mysql
mysql-connector-java
8.0.11
org.mybatis
mybatis
3.2.8
2.实体类和dao类
//接口类
public interface IuserDao {
List findAll();
}
//实体类
public class User implements Serializable {
private String id;
private String user_name;
private String password;
private String name;
private Integer age;
private Integer sex;
private String created;
private Date birthdday;
private String updated
get and set 方法
}
3.配置主配置文件
//这里要注意扫描的包是下划线
4.配置映射文件
5.数据库连接
创建数据库
CREATE DATABASE ssmdemo;
创建表
DROP TABLE IF EXISTS tb_user;
CREATE TABLE tb_user (
id char(32) NOT NULL,
user_name varchar(32) DEFAULT NULL,
password varchar(32) DEFAULT NULL,
name varchar(32) DEFAULT NULL,
age int(10) DEFAULT NULL,
sex int(2) DEFAULT NULL,
birthday date DEFAULT NULL,
created datetime DEFAULT NULL,
updated datetime DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
//插入的数据
INSERT INTO ssmdemo.tb_user ( id,user_name, password, name, age, sex, birthday, created, updated) VALUES ( '123','静静','123','yangtao','12',1, sysdate(), sysdate(),sysdate());
INSERT INTO ssmdemo.tb_user ( id,user_name, password, name, age, sex, birthday, created, updated) VALUES ( '456','秋秋','123','qiuqiu','12',2, sysdate(),sysdate(), sysdate());
6.测试类
package com.domain;
import com.dao.IuserDao;
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 java.io.InputStream;
import java.util.List;
/**
* * @description: TODO
* * @param ${tags}
* * @return ${return_type}
* * @throws
* * @author yangtao
* * @date $date$ $time$
*
*/
public class MybatisTest {
public static void main(String[] args) throws Exception {
// 指定全局配置文件
String resource = "mybatis-config.xml";
// 读取配置文件
InputStream inputStream = Resources.getResourceAsStream(resource);
// 构建sqlSessionFactory,用于加载配置信息
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
// 获取sqlSession,会话处理数据库的方法
IuserDao iuserDao=sqlSession.getMapper(IuserDao.class);
//查询数据
List user= iuserDao.findAll();
for (User u:user
) {
System.out.println(u.toString());
}
sqlSession.close();
}
}