后端开发-Mybatis开发之一
2018-12-29
Mybatis简单开发:我是在eclipse上进行Java项目开发
目录结构如下:
内容如下:
mysql.sql: 用于创建测试用的数据库以及表; 可以直接导入mysql,通过navicat工具或命令行;
create database chapter3; use chapter3; create table t_role ( id int(12) auto_increment, role_name varchar(60) not null, note varchar(256) null, primary key(id) ); insert into t_role(role_name, note) values('role_name_1', 'note_1');
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"> <!-- MyBatis配置文件 --> <configuration> <!-- 配置 --> <properties resource="db.properties"> </properties> <typeAliases><!-- 别名 --> <typeAlias alias="role" type="com.learn.ssm.chapter3.pojo.Role" /> </typeAliases> <!-- 数据库环境 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <!--引入db.properties配置文件前 --> <!-- <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/chapter3"/> <property name="username" value="root"/> <property name="password" value="root"/> --> <!--引入db.properties配置文件后 --> <property name="driver" value="${jdbc.driver}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.name}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments> <!-- 映射文件 --> <mappers> <mapper resource="com/learn/ssm/chapter3/mapper/RoleMapper.xml" /> <mapper class="com.learn.ssm.chapter3.mapper.RoleMapper2" /> </mappers> </configuration>
db.properties
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/chapter3 jdbc.name=root jdbc.password=123456
log4j.properties
#日志配置文件 log4j.rootLogger=DEBUG , stdout log4j.logger.org.mybatis=DEBUG log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n
Chapter3Main.java
package com.learn.ssm.chapter3.main; import org.apache.ibatis.session.SqlSession; import org.apache.log4j.Logger; import com.learn.ssm.chapter3.mapper.RoleMapper; import com.learn.ssm.chapter3.mapper.RoleMapper2; import com.learn.ssm.chapter3.pojo.Role; import com.learn.ssm.chapter3.utils.SqlSessionFactoryUtils; /** * 程序入口 * @author zc * @date 2018-12-29 */ public class Chapter3Main { public static void main(String[] args) { testRoleMapper(); testRoleMapper2(); } private static void testRoleMapper() { Logger log = Logger.getLogger(Chapter3Main.class); SqlSession sqlSession = null; try { sqlSession = SqlSessionFactoryUtils.openSqlSession(); RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class); Role role = roleMapper.getRole(1L); log.info(role.getRoleName()); } finally { if (sqlSession != null) { sqlSession.close(); } } } //ע��SQL���� private static void testRoleMapper2() { Logger log = Logger.getLogger(Chapter3Main.class); SqlSession sqlSession = null; try { sqlSession = SqlSessionFactoryUtils.openSqlSession(); RoleMapper2 roleMapper2 = sqlSession.getMapper(RoleMapper2.class); Role role = roleMapper2.getRole(1L); log.info(role.getRoleName()); } finally { if (sqlSession != null) { sqlSession.close(); } } } }
RoleMapper.java
package com.learn.ssm.chapter3.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import com.learn.ssm.chapter3.pojo.PageParams; import com.learn.ssm.chapter3.pojo.Role; import com.learn.ssm.chapter3.pojo.RoleParams; public interface RoleMapper { public int insertRole(Role role); public int deleteRole(Long id); public int updateRole(Role role); public Role getRole(Long id); public List<Role> findRoles(String roleName); //多个参数 public List<Role> findRolesByAnnotation(@Param("roleName") String rolename, @Param("note") String note); public List<Role> findRolesByMix(@Param("params") RoleParams roleParams, @Param("page") PageParams pageParams); }
RoleMapper2.java
package com.learn.ssm.chapter3.mapper; import org.apache.ibatis.annotations.Select; import com.learn.ssm.chapter3.pojo.Role; public interface RoleMapper2 { @Select("select id, role_name as roleName, note from t_role where id=#{id}") public Role getRole(Long 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.learn.ssm.chapter3.mapper.RoleMapper"> <insert id="insertRole" parameterType="role"> insert into t_role(role_name, note) values(#{roleName}, #{note}) </insert> <delete id="deleteRole" parameterType="long"> delete from t_role where id= #{id} </delete> <update id="updateRole" parameterType="role"> update t_role set role_name = #{roleName}, note = #{note} where id= #{id} </update> <select id="getRole" parameterType="long" resultType="role"> select id, role_name as roleName, note from t_role where id = #{id} </select> <select id="findRoles" parameterType="string" resultType="role"> select id, role_name as roleName, note from t_role where role_name like concat('%', #{roleName}, '%') </select> <select id="findRolesByAnnotation" resultType="role"> select id, role_name as roleName, note from t_role where role_name like concat('%', #{roleName}, '%') and note like concat('%', #{note}, '%') </select> <select id="findRolesByBean" parameterType="com.learn.ssm.chapter3.pojo.RoleParams" resultType="role"> select id, role_name as roleName, note from t_role where role_name like concat('%', #{roleName}, '%') and note like concat('%', #{note}, '%') </select> <select id="findRolesByMix" resultType="role"> select id, role_name as roleName, note from t_role where role_name like concat('%', #{params.roleName}, '%') and note like concat('%', #{params.note}, '%') limit #{page.start}, #{page.limit} </select> </mapper>
Role.java
package com.learn.ssm.chapter3.pojo; /** * POJO对象 * @author zc * */ public class Role { private Long id; private String roleName; private String note; /** setter and getter **/ public Long getId() { return id; } public void setId(Long 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; } }
PageParams .java
package com.learn.ssm.chapter3.pojo; public class PageParams { private int start; private int limit; public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } }
RoleParams .java
package com.learn.ssm.chapter3.pojo; public class RoleParams { private String roleName; private String note; 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; } }
SqlSessionFactoryUtils.java
package com.learn.ssm.chapter3.utils; import java.io.IOException; import java.io.InputStream; import org.apache.ibatis.datasource.pooled.PooledDataSource; import org.apache.ibatis.io.Resources; import org.apache.ibatis.mapping.Environment; import org.apache.ibatis.session.Configuration; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.apache.ibatis.transaction.TransactionFactory; import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory; import com.learn.ssm.chapter3.mapper.RoleMapper; import com.learn.ssm.chapter3.mapper.RoleMapper2; import com.learn.ssm.chapter3.pojo.Role; /** * 一个工具类,用于创建SqlSessionFactory和获取SqlSession对象 * @author zc * */ public class SqlSessionFactoryUtils { private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class; private static SqlSessionFactory sqlSessionFactory = null; private SqlSessionFactoryUtils() { } public static SqlSessionFactory getSqlSessionFactory() { synchronized (LOCK) { if (sqlSessionFactory != null) { return sqlSessionFactory; } String resource = "mybatis-config.xml"; InputStream inputStream; try { inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); return null; } return sqlSessionFactory; } } //��������SqlSessionFactory public static SqlSessionFactory getSqlSessionFactory2() { synchronized (LOCK) { //���ݿ����ӳ���Ϣ PooledDataSource dataSource = new PooledDataSource(); dataSource.setDriver("com.mysql.jdbc.Driver"); dataSource.setUsername("root"); dataSource.setPassword("123456"); dataSource.setUrl("jdbc:mysql://localhost:3306/chapter3"); dataSource.setDefaultAutoCommit(false); //����MyBatis��JDBC����ʽ TransactionFactory transactionFactory = new JdbcTransactionFactory(); Environment environment = new Environment("development", transactionFactory, dataSource); //����Configuration���� Configuration configuration = new Configuration(environment); //ע��һ��MyBatis�����ı��� configuration.getTypeAliasRegistry().registerAlias("role", Role.class); //����һ��ӳ���� configuration.addMapper(RoleMapper.class); configuration.addMapper(RoleMapper2.class); //ʹ��SqlSessionFactoryBuilder����SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); return sqlSessionFactory; } } public static SqlSession openSqlSession() { if (sqlSessionFactory == null) { getSqlSessionFactory(); } return sqlSessionFactory.openSession(); } }
1. 先引入mybatis和mysql相关jar包
2. 然后将mysql.sql导入到mysql中
3.运行