1.使用 XML 构建 SqlSessionFactory
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><!--别名--> <typeAliases alias="user" type="com.mybatis.po.User"/> </typeAliases> <!-- 数据库环境 --> <environments default="development"> <environment id="development"> <!-- 使用JDBC的事务管理 --> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <!-- MySQL数据库驱动 --> <property name="driver" value="com.mysql.jdbc.Driver" /> <!-- 连接数据库的URL --> <property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="1128" /> </dataSource> </environment> </environments> <!-- 将mapper文件加入到配置文件中 --> <mappers> <mapper resource="com/mybatis/mapper/UserMapper.xml" /> </mappers> </configuration>
SqlSessionFactory factory = null; String resource = "mybatis-config.xml"; InputStream is; try { InputStream is = Resources.getResourceAsStream(resource); factory = new SqlSessionFactoryBuilder().build(is); } catch (IOException e) { e.printStackTrace(); }
jdbc.properties
driverClassName=com.mysql.jdbc.Driver jdbc_url=jdbc:mysql://127.0.0.1:3306/db_testuse?Unicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull jdbc_username=root jdbc_password=123456
2.使用代码创建 SqlSessionFactory
// 数据库连接池信息 PooledDataSource dataSource = new PooledDataSource(); dataSource.setDriver("com.mysql.jdbc.Driver"); dataSource.setUsername("root"); dataSource.setPassword ("1128"); dataSource.setUrl("jdbc:mysql://localhost:3306/mybatis"); dataSource.setDefeultAutoCommit(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); //使用 SqlSessionFactoryBuilder 构建 SqlSessionFactory SqlSessionFactory SqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); return SqlSessionFactory;
历史推荐