Maven-Mybatis项目
- 引入Jar包,完整pom.xml如下
包括:mybatis-3.4.4
lombok.jar
mysql-connectot-java-5.0.2(注意,有些不兼容,更换版本即可)
<build></build>是为了解决eclipse转入idea时项目无法运行问题,请参考上一文章。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Mybatis</groupId>
<artifactId>ibatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>ibatis</name>
<url>http://maven.apache.org</url>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
- 配置Mybatis
注意url,以及扫描mapper包的位置。
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="***"/>
<property name="password" value="***"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--
<mapper resource="dao/UserMapper.xml"/>
-->
<package name="dao"/>
</mappers>
</configuration>
- 项目结构
UserMapper类暂时没有用到
![](https://img-blog.csdn.net/20171102204147558?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMzM1NjAxNjk=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
- 实体类User以及表结构
使用lombok.jar的getter/setter等减少代码量,更清晰
package domain;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
* @Author wsz
* @Des:
* @Date: 19:51 2017/11/2
*/
public class User implements Serializable{
private static final long serialVersionUID = 1L;
@Setter
@Getter
private Long id;
@Setter
@Getter
private String name;
@Setter
@Getter
private String realName;
@Setter
@Getter
private Long age;
@Setter
@Getter
private String des;
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", realName=" + realName
+ ", age=" + age + ", des=" + des + "]";
}
}
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`real_name` varchar(255) DEFAULT NULL,
`age` int(10) unsigned DEFAULT NULL,
`des` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=46 DEFAULT CHARSET=utf8;
- Mapper文件
<?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="dao.UserMapper">
<resultMap type="domain.User" id="BaseResultMap">
<id property ="id" column="id"/>
<result property="name" column="name"/>
<result property="realName" column="real_name"/>
<result property="age" column="age"/>
<result property="des" column="des"/>
</resultMap>
<parameterMap id="User" type="domain.User"/>
<sql id="Base_Column">
id,name,real_name,age,des
</sql>
<select id="findById" resultMap="BaseResultMap" parameterType="java.lang.Long">
select <include refid="Base_Column"/>
from user
where id = #{id}
</select>
<select id="findAll" resultMap="BaseResultMap">
select <include refid="Base_Column"/>
from user
</select>
<insert id="insertUser" parameterType="domain.User" useGeneratedKeys="true" keyProperty="id">
insert into user(id,name,real_name,age,des)
values (#{id},#{name},#{realName},#{age},#{des})
</insert>
<insert id="batchInsert" >
insert into user(id,name,real_name,age,des)
values
<foreach item="item" index="key" collection="list" open="" separator="," close="">
(#{item.id},#{item.name},#{item.realName},#{item.age},#{item.des})
</foreach>
</insert>
<select id="findByName" resultMap="BaseResultMap" parameterType="java.lang.String">
select <include refid="Base_Column"></include>
from user
where name =#{name}
</select>
</mapper>
- 测试操作类
package demo;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import domain.User;
public class Demo1 {
public static void main(String[] args) throws IOException {
String resource = "mybatis.xml";
InputStream is = Resources.getResourceAsStream(resource);
SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(is);
SqlSession session = sf.openSession();
try{
// //主键查找
// String str = "dao.UserMapper.findById";
// User user = session.selectOne(str, 1L);
// System.out.println(user.toString());
//批量插入
String batchInsert = "dao.UserMapper.batchInsert";
List<User> insertList = new ArrayList<User>();
for(int i = 0; i< 5 ; i++){
User u = new User();
u.setAge(i*10L);
u.setName(String.valueOf(i*i*i));
u.setRealName(String.valueOf('a'+i));
u.setDes("第几个:"+i);
insertList.add(u);
}
int insert = session.insert(batchInsert, insertList);
System.out.println(insert);
session.commit();
//查询所有
String str1 = "dao.UserMapper.findAll";
List<User> list = session.selectList(str1);
for (User u : list) {
System.out.println(u.toString());
}
//单一插入
// String str2 = "dao.UserMapper.insertUser";
// User i = new User();
// i.setName("dd");
// i.setRealName("大大");
// i.setAge(10L);
// i.setDes("VC可");
// int insert = session.insert(str2, i);
// System.out.println(insert);
// session.commit();
//equal查询
// String str3 = "dao.UserMapper.findByName";
// List<User> selectList = session.selectList(str3, "dd");
// System.out.println(selectList.size());
}finally{
session.close();
}
}
}
最后项目源码:链接:http://pan.baidu.com/s/1eSCixlo 密码:em7h
包括:mybatis-3.4.4
lombok.jar
mysql-connectot-java-5.0.2(注意,有些不兼容,更换版本即可)
<build></build>是为了解决eclipse转入idea时项目无法运行问题,请参考上一文章。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>Mybatis</groupId> <artifactId>ibatis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>ibatis</name> <url>http://maven.apache.org</url> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.xml</include> </includes> </resource> </resources> </build> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.0.2</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> <scope>provided</scope> </dependency> </dependencies> </project>
注意url,以及扫描mapper包的位置。
<?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> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8"/> <property name="username" value="***"/> <property name="password" value="***"/> </dataSource> </environment> </environments> <mappers> <!-- <mapper resource="dao/UserMapper.xml"/> --> <package name="dao"/> </mappers> </configuration>
UserMapper类暂时没有用到
使用lombok.jar的getter/setter等减少代码量,更清晰
package domain; import lombok.Getter; import lombok.Setter; import java.io.Serializable; /** * @Author wsz * @Des: * @Date: 19:51 2017/11/2 */ public class User implements Serializable{ private static final long serialVersionUID = 1L; @Setter @Getter private Long id; @Setter @Getter private String name; @Setter @Getter private String realName; @Setter @Getter private Long age; @Setter @Getter private String des; @Override public String toString() { return "User [id=" + id + ", name=" + name + ", realName=" + realName + ", age=" + age + ", des=" + des + "]"; } }
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`real_name` varchar(255) DEFAULT NULL,
`age` int(10) unsigned DEFAULT NULL,
`des` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=46 DEFAULT CHARSET=utf8;
<?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="dao.UserMapper"> <resultMap type="domain.User" id="BaseResultMap"> <id property ="id" column="id"/> <result property="name" column="name"/> <result property="realName" column="real_name"/> <result property="age" column="age"/> <result property="des" column="des"/> </resultMap> <parameterMap id="User" type="domain.User"/> <sql id="Base_Column"> id,name,real_name,age,des </sql> <select id="findById" resultMap="BaseResultMap" parameterType="java.lang.Long"> select <include refid="Base_Column"/> from user where id = #{id} </select> <select id="findAll" resultMap="BaseResultMap"> select <include refid="Base_Column"/> from user </select> <insert id="insertUser" parameterType="domain.User" useGeneratedKeys="true" keyProperty="id"> insert into user(id,name,real_name,age,des) values (#{id},#{name},#{realName},#{age},#{des}) </insert> <insert id="batchInsert" > insert into user(id,name,real_name,age,des) values <foreach item="item" index="key" collection="list" open="" separator="," close=""> (#{item.id},#{item.name},#{item.realName},#{item.age},#{item.des}) </foreach> </insert> <select id="findByName" resultMap="BaseResultMap" parameterType="java.lang.String"> select <include refid="Base_Column"></include> from user where name =#{name} </select> </mapper>
package demo; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import domain.User; public class Demo1 { public static void main(String[] args) throws IOException { String resource = "mybatis.xml"; InputStream is = Resources.getResourceAsStream(resource); SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(is); SqlSession session = sf.openSession(); try{ // //主键查找 // String str = "dao.UserMapper.findById"; // User user = session.selectOne(str, 1L); // System.out.println(user.toString()); //批量插入 String batchInsert = "dao.UserMapper.batchInsert"; List<User> insertList = new ArrayList<User>(); for(int i = 0; i< 5 ; i++){ User u = new User(); u.setAge(i*10L); u.setName(String.valueOf(i*i*i)); u.setRealName(String.valueOf('a'+i)); u.setDes("第几个:"+i); insertList.add(u); } int insert = session.insert(batchInsert, insertList); System.out.println(insert); session.commit(); //查询所有 String str1 = "dao.UserMapper.findAll"; List<User> list = session.selectList(str1); for (User u : list) { System.out.println(u.toString()); } //单一插入 // String str2 = "dao.UserMapper.insertUser"; // User i = new User(); // i.setName("dd"); // i.setRealName("大大"); // i.setAge(10L); // i.setDes("VC可"); // int insert = session.insert(str2, i); // System.out.println(insert); // session.commit(); //equal查询 // String str3 = "dao.UserMapper.findByName"; // List<User> selectList = session.selectList(str3, "dd"); // System.out.println(selectList.size()); }finally{ session.close(); } } }