Skip to content

Instantly share code, notes, and snippets.

@cheng470
Created February 7, 2015 08:05
Show Gist options
  • Save cheng470/7e380de050f953ce3851 to your computer and use it in GitHub Desktop.
Save cheng470/7e380de050f953ce3851 to your computer and use it in GitHub Desktop.
Mybatis 不使用配置文件例子
User [id=1, name=admin, password=admin]
User [id=2, name=zhangsan, password=zhangsan]
User [id=3, name=lisi, password=lisi]
package com.test.bean;
public class User {
private Integer id;
private String name;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password
+ "]";
}
}
-- --------------------------------------------------------
-- Host: 127.0.0.1
-- Server version: 5.6.15-enterprise-commercial-advanced - MySQL Enterprise Server - Advanced Edition (Commercial)
-- Server OS: Win64
-- HeidiSQL Version: 8.0.0.4396
-- --------------------------------------------------------
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
-- Dumping structure for table test.user
DROP TABLE IF EXISTS `user`;
CREATE TABLE IF NOT EXISTS `user` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`password` varchar(32) NOT NULL,
`email` varchar(32) NOT NULL,
`mobile` varchar(32) NOT NULL,
`status` tinyint(4) NOT NULL,
`createtime` datetime NOT NULL,
`changetime` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- Dumping data for table test.user: ~3 rows (approximately)
DELETE FROM `user`;
/*!40000 ALTER TABLE `user` DISABLE KEYS */;
INSERT INTO `user` (`id`, `name`, `password`, `email`, `mobile`, `status`, `createtime`, `changetime`) VALUES
(1, 'admin', 'admin', 'admin@test.com', '12312341234', 1, '2015-02-07 13:29:52', '2015-02-07 13:29:53'),
(2, 'zhangsan', 'zhangsan', 'zhangsan@test.com', '12312341234', 1, '2015-02-07 13:34:45', '2015-02-07 13:34:45'),
(3, 'lisi', 'lisi', 'lisi@test.com', '12312341234', 1, '2015-02-07 13:45:58', '2015-02-07 13:45:59');
/*!40000 ALTER TABLE `user` ENABLE KEYS */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IF(@OLD_FOREIGN_KEY_CHECKS IS NULL, 1, @OLD_FOREIGN_KEY_CHECKS) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
package com.test.dao.mybatis;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.ibatis.builder.StaticSqlSource;
import org.apache.ibatis.datasource.pooled.PooledDataSourceFactory;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultMap;
import org.apache.ibatis.mapping.ResultMapping;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
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 org.junit.Test;
import com.test.bean.User;
public class UserTestWithOutXml {
/**
* 获得MyBatis SqlSessionFactory
* SqlSessionFactory负责创建SqlSession,一旦创建成功,就可以用SqlSession实例来执行映射语句
* ,commit,rollback,close等方法。
*
* @return
*/
private static SqlSessionFactory getSessionFactory() {
// get datasource
Properties properties = new Properties();
properties.setProperty("driver", "com.mysql.jdbc.Driver");
properties.setProperty("url", "jdbc:mysql://127.0.0.1:3306/test");
properties.setProperty("username", "root");
properties.setProperty("password", "123456");
PooledDataSourceFactory pooledDataSourceFactory = new PooledDataSourceFactory();
pooledDataSourceFactory.setProperties(properties);
DataSource dataSource = pooledDataSourceFactory.getDataSource();
// create configuration
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();
ResultMapping resultMapping1 = new ResultMapping.Builder(configuration, "id", "id", Integer.class).build();
ResultMapping resultMapping2 = new ResultMapping.Builder(configuration, "name", "name", String.class).build();
ResultMapping resultMapping3 = new ResultMapping.Builder(configuration, "password", "password", String.class).build();
resultMappings.add(resultMapping1);
resultMappings.add(resultMapping2);
resultMappings.add(resultMapping3);
List<ResultMap> resultMaps = new ArrayList<ResultMap>();
ResultMap resultMap = new ResultMap.Builder(configuration, "user", User.class, resultMappings).build();
resultMaps.add(resultMap);
String sql = "select id, name, password from user";
SqlSource sqlSource = new StaticSqlSource(configuration, sql);
MappedStatement userMapper = new MappedStatement.Builder(configuration, "User.listUser", sqlSource, SqlCommandType.SELECT)
.resultMaps(resultMaps)
.build();
configuration.addMappedStatement(userMapper);
// get factory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
return sqlSessionFactory;
}
@Test
public void test() {
SqlSession session = getSessionFactory().openSession();
List<User> users = session.selectList("User.listUser");
for (User u: users) {
System.out.println(u);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment