初學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">
		select
		id,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 where
		id=#{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 Singleton
		InputStream 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();
		}
	}
}






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章