初学MyBatis之HelloWorld

官方下载

https://github.com/mybatis/mybatis-3/releases

整个程序结构如下:

1 准备测试用的数据库表

创建表t_role并添加测试数据

CREATE TABLE `t_role` (

  `id` int(10) NOT NULL,

  `rolename` varchar(255) DEFAULT NULL,

  `note` varchar(255) DEFAULT NULL,

  PRIMARY KEY (`id`)

) ENGINE=MyISAM DEFAULT CHARSET=latin1;

 

-- ----------------------------

-- Records of t_role

-- ----------------------------

INSERT INTO `t_role` VALUES ('4', 'wangbo', null);

INSERT INTO `t_role` VALUES ('2', 'zhuorui', '222');

INSERT INTO `t_role` VALUES ('3', 'wujun', '333');

2 引用对应的jar

3 添加log4j.properties

log4j.properties添加到src

log4j.rootLogger=DEBUG, stdout,logfile

og4j.appender.stdout=org.apache.log4j.ConsoleAppender

log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] \n %m%n

 

log4j.appender.logfile=org.apache.log4j.RollingFileAppender

log4j.appender.logfile.MaxFileSize=1024KB

log4j.appender.logfile.MaxBackupIndex=10

log4j.appender.logfile.layout=org.apache.log4j.PatternLayout

log4j.appender.logfile.File=logs/main.log

log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] \n %m%n

4 添加pojo

public class Role {private int id;private String rolename;private String note;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getRolename() {return rolename;}public void setRolename(String rolename) {this.rolename = rolename;}public String getNote() {return note;}public void setNote(String note) {this.note = note;}
}

5 MyBatis配置文件mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><typeAliases><typeAlias alias="role" type="com.hinner.test.po.Role" /></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC" /><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://192.168.8.214:3306/test" /><property name="username" value="*****" /><property name="password" value="*****" /></dataSource></environment></environments><mappers><mapper resource="com/hinner/test/mapper/roleMapper.xml" /></mappers>
</configuration>

6 创建Mapper类及配置

RoleMapper

public interface RoleMapper {public Role getRole(int id);public int insertRole(Role role);public int deleteRole(int id);
}

配置roleMapper.xml

?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hinner.test.mapper.RoleMapper"><select id="getRole" parameterType="int" resultType="role">selectid,rolename,note from t_role where id=#{id}</select><insert id="insertRole" parameterType="role">insert into t_role(id,rolename,note)values(#{id},#{rolename},#{note})</insert><delete id="deleteRole" parameterType="int">delete from t_role whereid=#{id}</delete>
</mapper>

7 创建SqlSessionFactoryUtil工具类

public class SqlSessionFactoryUtil {public static Logger logger = Logger.getLogger(SqlSessionFactoryUtil.class);private static SqlSessionFactory factory = null;public static final String PATH_MYBATIS = "mybatis-config.xml";private final static Class CLASS_LOCK = SqlSessionFactoryUtil.class;public static void init() {getSqlSessionFactory();}public static SqlSessionFactory getSqlSessionFactory() {if (factory != null)return factory;// then create a SingletonInputStream inputStream = null;try {inputStream = Resources.getResourceAsStream(PATH_MYBATIS);} catch (IOException e) {logger.error(e.getMessage(), e);}synchronized (CLASS_LOCK) {if (factory == null)factory = new SqlSessionFactoryBuilder().build(inputStream);}return factory;}public static SqlSession getSession() {return getSqlSessionFactory().openSession();}
}

8 TestMain

public class MainTest {public static void main(String[] args) {try {SqlSessionFactoryUtil.init();} catch (Exception ex) {ex.printStackTrace();System.exit(0);}SqlSession sqlSession = null;try {sqlSession = SqlSessionFactoryUtil.getSession();RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);// Role role = mapper.getRole(1);// System.out.println(role.getRolename());// int d = mapper.deleteRole(1);// System.out.println(d);Role role = new Role();role.setId(4);role.setRolename("wangbo");role.setNote(null);int i = mapper.insertRole(role);System.out.println(i);sqlSession.commit();} catch (Exception ex) {ex.printStackTrace();sqlSession.rollback();} finally {if (sqlSession != null)sqlSession.close();}}
}