//转载请注明出处:https://www.cnblogs.com/nreg/p/11156167.html
1.项目结构区别:
2.开发区别:
注:其中原始dao开发的实现类UserDaoImpl 与动态代理开发的工具类UserService的第16行-第27行代码可以提炼出来,
3.工厂类:Factory
1 public class Factory { 2 private final static Class<Factory> lock = Factory.class; 3 private static SqlSessionFactory sqlSessionFactory = null; 4 private Factory() {} 5 6 public static SqlSessionFactory getSqlSessionFactory() { 7 synchronized (lock) { 8 if (sqlSessionFactory != null) { 9 return sqlSessionFactory; 10 } 11 //加载核心配置文件 12 String resource = "mybatis-config.xml"; 13 InputStream inputStream; 14 try { 15 inputStream = Resources.getResourceAsStream(resource); 16 //创建SqlsessionFactory工厂 17 sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); 18 } catch (IOException e) { 19 e.printStackTrace(); 20 return null; 21 } 22 //对外提供一个工厂 23 return sqlSessionFactory; 24 } 25 } 26 27 //对外提供一个Sqlsession会话 28 public static SqlSession getSession() { 29 if (sqlSessionFactory == null) { 30 getSqlSessionFactory(); 31 } 32 return sqlSessionFactory.openSession(); 33 } 34 }
工厂类使用示例:
4.Mybatis的核心配置文件:mybatis-config.xml
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 6 <configuration> 7 <properties resource="jdbc.properties"></properties> 8 9 <!--environments元素:配置Mybatis的运行环境--> 10 <!--可配置多套运行环境,将SQL映射到多个不同的数据库上,但必须通过default属性指定默认运行环境--> 11 <environments default="development"> <!--default属性指定默认运行环境的id--> 12 <environment id="development"> <!-- 第一套运行环境的id--> 13 <transactionManager type="JDBC"></transactionManager> <!--事务管理器配置--> 14 <dataSource type="POOLED"> <!--数据源(连接池)配置--> 15 <property name="driver" value="${jdbc.driver}"/> 16 <property name="url" value="${jdbc.url}"/> 17 <property name="username" value="${jdbc.username}"/> 18 <property name="password" value="${jdbc.password}"/> 19 </dataSource> 20 </environment> 21 </environments> 22 23 <!--mappers元素:配置mapper映射器的xml映射文件 以动态代理开发为例,原始dao开发配置方法相同--> 24 <mappers> 25 <!--方式一:使用resource配置映射文件--> 26 <mapper resource="com/nreg/mapper/UserMapper.xml"></mapper> 27 <!--方式二:使用url配置映射文件--> 28 <mapper url="D:Mybatis-agency-easysrcmainjavacom regmapperUserMapper.xml"></mapper> 29 <!--方式三:多个映射器的使用:开启扫描--> 30 <package name="com.nreg.mapper"/> 31 </mappers> 32 </configuration>
5.外部属性文件:jdbc
1 jdbc.driver=com.mysql.jdbc.Driver 2 jdbc.url=jdbc:mysql://localhost:3306/crud?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8 3 jdbc.username=root 4 jdbc.password=123456
6.日志文件:log4j
1 ### 设置Logger输出级别和输出目的地 ### debug更详细,如果把debug改为info,则打印出的表数据遇到字符串就不显示,此外还有log4j.log文件 2 log4j.rootLogger=debug,stdout 3 4 ### 把日志信息输出到控制台 ### 5 log4j.appender.stdout=org.apache.log4j.ConsoleAppender 6 #log4j.appender.stdout.Target=System.err 7 log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout 8 9 ### 把日志信息输出到文件:log4j.log ### 10 log4j.appender.logfile=org.apache.log4j.FileAppender 11 log4j.appender.logfile.File=log4j.log 12 log4j.appender.logfile.layout=org.apache.log4j.PatternLayout 13 log4j.appender.logfile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %F %p %m%n 14 15 ###显示SQL语句部分 ### 16 #第一行:xml映射文件所在包 17 log4j.logger.com.nreg.sqlMap=DEBUG 18 log4j.logger.java.sql.Connection=DEBUG 19 log4j.logger.java.sql.Statement=DEBUG 20 log4j.logger.java.sql.PreparedStatement=DEBUG 21 log4j.logger.java.sql.ResultSet=DEBUG
7.开发用crud模板:
1).接口:
1 //增 2 boolean addUser(User user); 3 //删 4 boolean deleteUserById(int id); 5 //改 6 boolean updateUserById(User user); 7 //查:按id查一个 8 User getUserById(int id); 9 //查:查所有 10 List<User> getUser();
2).xml映射文件:
<!--增--> <insert id="addUser" parameterType="com.nreg.bean.User" useGeneratedKeys="true" keyProperty="id"> insert into user values(null,#{username},#{password}) </insert> <!--删--> <delete id="deleteUserById" parameterType="int"> delete from user where id = #{id} </delete> <!--改--> <update id="updateUserById" parameterType="com.nreg.bean.User"> update user set username = #{username},password = #{password} where id=#{id} </update> <!--查:按id查--> <select id="getUserById" parameterType="int" resultType="com.nreg.bean.User"> select * from user where 1=1 and id = #{id}<!--注:1=1 and:用于防止后面条件不成立造成SQL语句错误--> </select> <!--查:查所有--> <select id="getUser" resultType="com.nreg.bean.User"> select * from user </select>
3).动态代理开发:UserService工具类:
1 public class UserService { 2 3 SqlSession sqlsession=null; 4 //增 5 public boolean addUser(User user) { 6 try { 7 //1.通过工厂获取会话 8 sqlsession= Factory.getSession(); 9 //2.从会话中获取接口的代理对象 10 UserMapper userMapper=sqlsession.getMapper(UserMapper.class); 11 //3.通过代理对象操作数据库 12 userMapper.addUser(user); 13 //提交事务 14 sqlsession.commit(); 15 return true; 16 } catch (Exception e) { 17 //回滚 18 if(sqlsession !=null){ 19 sqlsession.rollback(); 20 } 21 return false; 22 }finally{ 23 //关闭连接,释放资源 24 if(sqlsession!=null){ 25 sqlsession.close(); 26 } 27 } 28 } 29 30 //删 31 public boolean deleteUserById(int id) { 32 try { 33 sqlsession= Factory.getSession(); 34 UserMapper userMapper=sqlsession.getMapper(UserMapper.class); 35 boolean tf=userMapper.deleteUserById(id); 36 sqlsession.commit(); 37 return tf; 38 } catch (Exception e) { 39 if(sqlsession!=null){ 40 sqlsession.rollback(); 41 } 42 return false; 43 }finally{ 44 if(sqlsession!=null){ 45 sqlsession.close(); 46 } 47 } 48 } 49 50 //改 51 public boolean updateUserById(User user) { 52 53 try { 54 sqlsession= Factory.getSession(); 55 UserMapper userMapper=sqlsession.getMapper(UserMapper.class); 56 userMapper.updateUserById(user); 57 sqlsession.commit(); 58 return true; 59 } catch (Exception e) { 60 if(sqlsession !=null){ 61 sqlsession.rollback(); 62 } 63 return false; 64 }finally{ 65 if(sqlsession !=null){ 66 sqlsession.close(); 67 } 68 } 69 } 70 71 //查:按id查一个 72 public User getUserById(int id) { 73 74 try { 75 sqlsession= Factory.getSession(); 76 UserMapper userMapper=sqlsession.getMapper(UserMapper.class); 77 User user = userMapper.getUserById(id); 78 return user; 79 80 } catch (Exception e) { 81 if(sqlsession!=null){ 82 sqlsession.rollback(); 83 } 84 e.printStackTrace(); 85 return null; 86 }finally{ 87 if(sqlsession !=null){ 88 sqlsession.close(); 89 } 90 } 91 } 92 93 //查:查所有 94 public List<User> getUser() { 95 96 try { 97 sqlsession = Factory.getSession(); 98 List<User> list = null; 99 UserMapper userMapper=sqlsession.getMapper(UserMapper.class); 100 list = userMapper.getUser(); 101 return list; 102 } catch (Exception e) { 103 if(sqlsession!=null){ 104 sqlsession.rollback(); 105 } 106 return null; 107 }finally{ 108 if(sqlsession !=null){ 109 sqlsession.close(); 110 } 111 } 112 } 113 }
4).原始dao开发:UserDaoImpl实现类:
1 public class UserDaoImpl implements UserDao { 2 3 SqlSession sqlsession = null; 4 //增: 5 @Override 6 public boolean addUser(User user) { 7 try { 8 //1.通过工厂获取会话 9 sqlsession = Factory.getSession(); 10 //2.通过会话操作数据库 11 sqlsession.insert("addUser", user); 12 //提交事务:增删改都需要提交事务 13 sqlsession.commit(); 14 return true; 15 } catch (Exception e) { 16 //回滚 17 if (sqlsession != null) { 18 sqlsession.rollback(); 19 } 20 return false; 21 } finally { 22 //关闭连接,释放资源 23 if (sqlsession != null) { 24 sqlsession.close(); 25 } 26 } 27 } 28 29 //删 30 @Override 31 public boolean deleteUserById(int id) { 32 try { 33 //1.通过工厂获取会话 34 sqlsession = Factory.getSession(); 35 //2.通过会话操作数据库 36 sqlsession.delete("deleteUserById",id); 37 //3.提交事务 38 sqlsession.commit(); 39 return true; 40 } catch (Exception e) { 41 if (sqlsession != null) { 42 //回滚 43 sqlsession.rollback(); 44 } 45 return false; 46 } finally { 47 if (sqlsession != null) { 48 //关闭连接,释放资源 49 sqlsession.close(); 50 } 51 } 52 } 53 54 55 //改: 56 @Override 57 public boolean updateUserById(User user) { 58 try { 59 sqlsession = Factory.getSession(); 60 sqlsession.update("updateUserById", user); 61 sqlsession.commit(); 62 return true; 63 } catch (Exception e) { 64 if (sqlsession != null) { 65 sqlsession.rollback(); 66 } 67 return false; 68 } finally { 69 if (sqlsession != null) { 70 sqlsession.close(); 71 } 72 } 73 } 74 75 //查:按id查 76 @Override 77 public User getUserById(int id) { 78 try { 79 sqlsession = Factory.getSession(); 80 User user = sqlsession.selectOne("getUserById",id); 81 return user; 82 } catch (Exception e) { 83 if (sqlsession != null) { 84 sqlsession.rollback(); 85 } 86 return null; 87 } finally { 88 if (sqlsession != null) { 89 sqlsession.close(); 90 } 91 } 92 } 93 94 //查:查所有 95 @Override 96 public List<User> getUser() { 97 try { 98 sqlsession = Factory.getSession(); 99 List<User> list = sqlsession.selectList("getUser"); 100 return list; 101 } catch (Exception e) { 102 if (sqlsession != null) { 103 sqlsession.rollback(); 104 } 105 return null; 106 } finally { 107 if (sqlsession != null) { 108 sqlsession.close(); 109 } 110 } 111 } 112 }
结。