• 初探MyBatis之HelloWorld(二)


    二、不使用 XML 构建 SqlSessionFactory

    不使用xml构建SqlSessionFactory的话,就要用java代码来连接数据库。我这里直接new DataSorce()接口实现getConnection()方法(不知道对不对,反正实验证明,可行)。

    EmployeeDataSourceFactory.java:

     1 package yyc.mybatis.util;
     2 
     3 import java.io.PrintWriter;
     4 import java.sql.Connection;
     5 import java.sql.DriverManager;
     6 import java.sql.SQLException;
     7 import java.sql.SQLFeatureNotSupportedException;
     8 import java.util.logging.Logger;
     9 
    10 import javax.sql.DataSource;
    11 
    12 public class EmployeeDataSourceFactory {
    13     
    14     public static DataSource getEmployeeDataSorce(){
    15         DataSource ds=new DataSource() {
    16             
    17             public <T> T unwrap(Class<T> iface) throws SQLException {
    18                 // TODO Auto-generated method stub
    19                 return null;
    20             }
    21             
    22             public boolean isWrapperFor(Class<?> iface) throws SQLException {
    23                 // TODO Auto-generated method stub
    24                 return false;
    25             }
    26             
    27             public void setLoginTimeout(int seconds) throws SQLException {
    28                 // TODO Auto-generated method stub
    29                 
    30             }
    31             
    32             public void setLogWriter(PrintWriter out) throws SQLException {
    33                 // TODO Auto-generated method stub
    34                 
    35             }
    36             
    37             public Logger getParentLogger() throws SQLFeatureNotSupportedException {
    38                 // TODO Auto-generated method stub
    39                 return null;
    40             }
    41             
    42             public int getLoginTimeout() throws SQLException {
    43                 // TODO Auto-generated method stub
    44                 return 0;
    45             }
    46             
    47             public PrintWriter getLogWriter() throws SQLException {
    48                 // TODO Auto-generated method stub
    49                 return null;
    50             }
    51             
    52             public Connection getConnection(String username, String password) throws SQLException {
    53                 // TODO Auto-generated method stub
    54                 return null;
    55             }
    56             
    57             public Connection getConnection() throws SQLException {
    58                 try {
    59                     Class.forName("com.mysql.jdbc.Driver");
    60                     String url="jdbc:mysql:///mybatis";
    61                     String user="root";
    62                     String password="123";
    63                     Connection connection = DriverManager.getConnection(url, user, password);
    64                     return connection;
    65                 } catch (ClassNotFoundException e) {
    66                     e.printStackTrace();
    67                 }
    68                 return null;
    69             }
    70         };
    71         return ds;
    72     }
    73 }

    在第一种时,写了一个xml的SQL映射文件(EmployeeMapperXml.xml),现在既然不用xml了,就需要另一种你方式来映射SQL吧,mybatis提供面向接口编程的方式。官方文档中是这样说的:

    它们的映射的语句可以不需要用 XML 来做,取而代之的是可以使用 Java 注解。比如:
    package org.mybatis.example;
    public interface BlogMapper {
      @Select("SELECT * FROM blog WHERE id = #{id}")
      Blog selectBlog(int id);
    }

    我这里写一接口:

    EmployeeMapper.java:

    package yyc.mybatis.mapper;
    import org.apache.ibatis.annotations.Select;
    import yyc.mybatis.bean.Employee;
    public interface EmployeeMapper {
    
        @Select("SELECT id,last_name lastName,gender,email FROM tb1_employee WHERE id= #{id}")
        public Employee selectOne(Integer id);
    }

    测试方法(不用xml来得到SqlSessionFactory的方式也不一样):

    @Test
        public void testJavaConfig(){
            DataSource dataSource = EmployeeDataSourceFactory.getEmployeeDataSorce();
            TransactionFactory transactionFactory = new JdbcTransactionFactory();
            Environment environment = new Environment("development", transactionFactory, dataSource);
            Configuration configuration = new Configuration(environment);
            configuration.addMapper(EmployeeMapper.class);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        
            
            //2.获取sqlSession实例,能直接执行已经映射的sql语句
                    SqlSession openSession = sqlSessionFactory.openSession();
                    
                    try {
                        EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
                        Employee employee = mapper.selectOne(3);
                        System.out.println(employee);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }finally {
                        openSession.close();
                    }
        }

    输出:

    Employee [id=3, lastName=mac, gender=1, email=cc@163.com]

    这样就完全脱离了两个xml配置文件实现查询数据库。

  • 相关阅读:
    Borland C++ Builder Practical learning series
    vmware打开vmx文件不能创建虚拟机的问题
    c3p0 连接数据库失败的问题
    外在 挺直背和走路的问题
    JAVAWEB tomcat服务器启动错误原因总结
    JAVAWEB 项目注册登录模块问题总结
    JAVA eclipse Maven项目红叹号解决方案
    JAVA 文件读取写入后 md5值不变的方法
    Git的安装配置(win环境)
    JAVA 静态方法和实例方法的区别 (图表)
  • 原文地址:https://www.cnblogs.com/hyyq/p/6718449.html
Copyright © 2020-2023  润新知