Java的MyBatis框架项目搭建与hellow world示例
程序员文章站
2024-03-11 22:41:37
新建项目(我使用的是maven项目)mybatis-study-01
一、加入mybatis与mysql-connector依赖包到pom文件
新建项目(我使用的是maven项目)mybatis-study-01
一、加入mybatis与mysql-connector依赖包到pom文件
<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>mybatis-study-01</artifactid> <version>0.0.1-snapshot</version> <packaging>jar</packaging> <name>mybatis-01</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceencoding>utf-8</project.build.sourceencoding> </properties> <dependencies> <dependency> <groupid>junit</groupid> <artifactid>junit</artifactid> <version>4.10</version> <scope>test</scope> </dependency> <dependency> <groupid>org.mybatis</groupid> <artifactid>mybatis</artifactid> <version>3.2.3</version> </dependency> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>5.1.27</version> </dependency> </dependencies> </project>
二、创建数据库mybatis-test
新建一张user表用于测试。建表sql如下:
create table `user` ( `id` int(11) not null auto_increment, `password` varchar(255) default null, `user_name` varchar(50) default null, `user_age` int(11) default null, `user_address` varchar(200) default null, primary key (`id`), unique key `username` (`user_name`) ) en
插入一条数据
insert into `user` values ('1', '123131', 'summer', '100', 'shanghai,pudong');
三、在项目中编写pojo对象。
package com.zf.mybatis.pojo; public class user { private int id; private string password ; private string username; private string userage; private string useraddress; public int getid() { return id; } public void setid(int id) { this.id = id; } public string getusername() { return username; } public void setusername(string username) { this.username = username; } public string getuserage() { return userage; } public void setuserage(string userage) { this.userage = userage; } public string getuseraddress() { return useraddress; } public void setuseraddress(string useraddress) { this.useraddress = useraddress; } public string getpassword() { return password; } public void setpassword(string password) { this.password = password; } }
四、编写pojo对应的映射文件user.xml
<?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="com.zf.mybatis.pojo.usermapper"> <!-- 使用sql标签可以将公共的sql提取出来复用 --> <sql id="queryfields"> id , password , user_name as username , user_age as userage , user_address as useraddress </sql> <select id="selectbyid" parametertype="int" resulttype="user"> select <include refid="queryfields"/> from `user` where id = #{id} </select> <insert id="add" parametertype="user" usegeneratedkeys="true" keyproperty="id" > insert into `user` (password , user_name , user_age , user_address) values(#{password} , #{username} , #{userage} , #{useraddress} ) </insert> <update id="update" parametertype="user" > update `user` set password = #{password} , user_name = #{username}, user_age = #{userage}, user_address = #{useraddress} where id = #{id} </update> <delete id="deletebyid" parametertype="int"> delete from `user` where id = #{id} </delete> </mapper>
注意:上面的namespace的值为com.zf.mybatis.pojo.usermapper,可以自定义 ,usermapper不是一个类,不需要存在的。
另外,mybatis会将从数据库查询出来的记录根据列名与pojo中的字段进行匹配, 所以上面的user_name,user_age ,user_address这几个字段都取了别名,跟pojo中的字段相对应。 如果不起别名, 查询出来的对象,这几个字段是没有值的。
五、编写mybatis的配置文件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> <typealias alias="user" type="com.zf.mybatis.pojo.user"/> </typealiases> <!-- 数据库配置信息 --> <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://127.0.0.1:3306/mybatis-test"/> <property name="username" value="root"/> <property name="password" value="root"/> </datasource> </environment> </environments> <!-- 映射文件 --> <mappers> <mapper resource="conf/user.xml"/> </mappers> </configuration>
在该配置文件中配置了数据库的链接方式,以及注册所有的映射文件,还可以设置mybatis的一些参数。
现在就可以编写测试类了。来测试一下。
package com.zf.mybatis; import java.io.ioexception; import java.io.reader; 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 org.junit.before; import org.junit.test; import com.zf.mybatis.pojo.user; public class testmybatis { private sqlsessionfactory sqlsessionfactory; private reader reader; @before public void init(){ try { reader = resources.getresourceasreader("mybatis-config.xml"); sqlsessionfactory = new sqlsessionfactorybuilder().build(reader); } catch (ioexception e) { e.printstacktrace(); } } @test public void testqueryuser(){ sqlsession session = sqlsessionfactory.opensession(); try { user user = (user) session.selectone("com.zf.mybatis.pojo.usermapper.selectbyid" ,1); system.out.println(user.getuseraddress()); system.out.println(user.getusername()); } finally { session.close(); } } @test public void testinsertuser(){ sqlsession session = sqlsessionfactory.opensession(); try { user user = new user() ; user.setusername("abcde"); user.setuserage(15) ; user.setuseraddress("hangzhou/zhejiang"); user.setpassword("123456"); //返回值是记录条数 int resultcount = session.insert("com.zf.mybatis.pojo.usermapper.add", user ); session.commit() ; system.out.printf("userid:%d,总记录条数:%d" , user.getid() , resultcount); //获取插入对象的id } finally { session.close(); } } @test public void testupdateuser(){ sqlsession session = sqlsessionfactory.opensession(); try { user user = new user() ; user.setid(5) ; user.setusername("updatename"); user.setuserage(101) ; user.setuseraddress("shenzhen/guangdong"); user.setpassword("000000"); //返回值是修改条数 int updatecount = session.update("com.zf.mybatis.pojo.usermapper.update", user ); session.commit() ; system.out.printf("修改条数:%d" ,updatecount); } finally { session.close(); } } @test public void testdelete(){ sqlsession session = sqlsessionfactory.opensession(); try { //返回值是删除条数 int deletecount = session.update("com.zf.mybatis.pojo.usermapper.deletebyid", 4 ); session.commit() ; system.out.printf("删除条数:%d" ,deletecount ); } finally { session.close(); } } }
运行testqueryuser结果如下:
shanghai,pudong summer
到此,一个mybatis的helloworld类型的小程序就出来了。
ps:mybaits配置文件报错解决
mybaits的配置文件校验很诡异,节点的位置还有要求
如下,会报错:
the content of element type "configuration" must match "(properties?,settings?,typealiases?,typehandlers?,objectfactory?,objectwrapperfactory?,plugins?,environments?,mappers?)". <?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="oracle.jdbc.driver.oracledriver"/> <property name="url" value="jdbc:oracle:thin:@xx:1521:xx"/> <property name="username" value="ireport"/> <property name="password" value="xxxx"/> </datasource> </environment> </environments> <typealiases> <typealias type="com.ice.stat.online.model.eventflag" alias="eventflag"/> </typealiases> <mappers> <mapper resource="com/ice/stat/online/model/hbm/eventflagmapper.xml"/> </mappers> </configuration>
把typealiases放到最上面就好了说:
<?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> <typealias type="com.ice.stat.online.model.eventflag" alias="eventflag"/> </typealiases> <environments default="development"> <environment id="development"> <transactionmanager type="jdbc"/> <datasource type="pooled"> <property name="driver" value="oracle.jdbc.driver.oracledriver"/> <property name="url" value="jdbc:oracle:thin:@xx:1521:xx"/> <property name="username" value="ireport"/> <property name="password" value="xxxx"/> </datasource> </environment> </environments> <mappers> <mapper resource="com/ice/stat/online/model/hbm/eventflagmapper.xml"/> </mappers> </configuration>