eclipse创建一个简单的MyBatis项目
1.创建一个web应用程序
输入项目名称
2.在lib文件夹中添加jar包
链接:https://pan.baidu.com/s/1AjhcveNCVokizsrrF_-YLA
提取码:gza8
3.在src文件夹中创建com.demo.po,com.demo.mapper,com.demo.dao三个包,并创建MyBatis框架配置文件mybatis-config.xml文件,在mapper目录下创建数据实体映射文件CommodityStorageMapper.xml,在po目录下创建名为CommodityStorage的实体类。如下图所示:
4.在MySQL中创建数据库my_db
create database if not exists my_db character set utf8 collate utf8_general_ci; use my_db; drop table if exists commodity_storage; create table commodity_storage( commodity_id varchar(45) primary key, commodity_name varchar(45) not null, enter_date date not null, commodity_amount int(10) UNSIGNED not null, commodity_supplier varchar(45) not null )ENGINE=innoDB default charset=utf8; insert into commodity_storage values ('C001','帽子','2020-03-08',150,'新丰慧'), ('C002','运动裤','2020-05-06',230,'新丰慧'), ('C003','衬衣','2020-07-20',80,'天利'), ('C004','口罩','2020-03-08',1500,'万源'), ('C005','遮阳镜','2020-05-06',68,'利风'), ('C006','运动鞋','2020-03-08',800,'利风'), ('C007','风衣','2020-03-08',460,'天利'), ('C008','救生圈','2020-05-06',180,'奥体'), ('C009','玩具','2020-03-08',390,'奥体');
5.mybatis-config.xml配置文件的编写
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> <!-- 默认使用的环境 ID(比如:default="development") 也就是说我们可以配置多套<environment>环境--> <environments default="my_dev"> <!-- 每个 environment 元素定义的环境 ID --> <environment id="my_dev"> <!-- transactionManager 事务管理器 type的值有JDBC和MANAGED JDBC – 这个配置直接使用了 JDBC 的提交和回滚设施,它依赖从数据源获得的连接来管理事务作用域。 --> <transactionManager type="JDBC"/> <!-- dataSourcedataSource 数据源 dbcp c3p0 druid type="[UNPOOLED|POOLED|JNDI]" POOLED意思有连接池的连接 UNPOOLED意思没有连接池的连接 --> <dataSource type="POOLED"> <!-- JDBC 驱动--> <property name="driver" value="com.mysql.jdbc.Driver"/> <!-- url数据库的 JDBC URL地址。--> <property name="url" value="jdbc:mysql://localhost:3306/my_db"/> <property name="username" value="root"/> <property name="password" value="123456"/> <!-- defaultTransactionIsolationLevel – 默认的连接事务隔离级别。–>--> <!-- <property name="defaultTransactionIsolationLevel" value=""/>--> <!-- defaultNetworkTimeout – 等待数据库操作完成的默认网络超时时间(单位:毫秒)–>--> <!-- <property name="efaultNetworkTimeout" value=""/>--> </dataSource> </environment> </environments> <mappers> <!-- 使用相对于类路径的资源引用 --> <mapper resource="com/demo/mapper/CommodityStorageMapper.xml"/> <!-- 使用完全限定资源定位符(URL) 不推荐使用 <mapper url="E:\JetBrains\mybatis学习\Mybatis-study\Mybatis-03\src\main\java\asia\xiaojiang\mybatis03\dao\UserMapper.xml"/> --> <!-- 使用映射器接口实现类的完全限定类名 使用注意点: 接口和其配置文件必须同名, 必须在同一个包下 --> <!-- <mapper class="asia.xiaojiang.mybatis03.dao.UserMapper"/>--> <!-- 将包内的映射器接口实现全部注册为映射器 使用包扫描注意点: 接口和其配置文件必须同名, 必须在同一个包下 --> <!-- <package name="asia.xiaojiang.mybatis03.dao"/>--> </mappers> </configuration>
6.关系数据实体类文件CommodityStorage.java
CommodityStorage.java
package com.demo.po; import java.util.Date; public class CommodityStorage { private String commodityId; private String commodityName; private Date enterDate; private Integer commodityAmount; private String commoditySupplier; public String getCommodityId() { return commodityId; } public void setCommodityId(String commodityId) { this.commodityId = commodityId; } public String getCommodityName() { return commodityName; } public void setCommodityName(String commodityName) { this.commodityName = commodityName; } public Date getEnterDate() { return enterDate; } public void setEnterDate(Date enterDate) { this.enterDate = enterDate; } public Integer getCommodityAmount() { return commodityAmount; } public void setCommodityAmount(Integer commodityAmount) { this.commodityAmount = commodityAmount; } public String getCommoditySupplier() { return commoditySupplier; } public void setCommoditySupplier(String commoditySupplier) { this.commoditySupplier = commoditySupplier; } }
7.关系数据实体映射文件CommodityStorageMapper.xml
CommodityStorageMapper.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.demo.po.CommodityStorage"> <!-- 插入商品库存信息 --> <insert id="insertCommodity" parameterType="com.demo.po.CommodityStorage"> insert into commodity_storage values(#{commodityId},#{commodityName},#{enterDate}, #{commodityAmount},#{commoditySupplier}) </insert> <!-- 更新商品库存操作 --> <update id="updateCommodity" parameterType="com.demo.po.CommodityStorage"> update commodity_storage set commodity_amount=#{commodityAmount} where commodity_supplier=#{commoditySupplier} </update> <!-- 删除商品库存操作 --> <delete id="deleteCommodity" parameterType="String"> delete from commodity_storage where commodity_name=#{commodityName} </delete> <!-- 检索单条商品库存操作 --> <select id="findCommodityById" parameterType="String" resultType="com.demo.po.CommodityStorage"> select commodity_id as commodityId, commodity_name as commodityName enter_date as enterDate,commodity_amount as commodityAmount, commodity_supplier as commoditySupplier from commodity_storage where commodity_id=#{commodityId} </select> <!-- 检索多条商品库存操作 --> <select id="findCommodityByAmount" parameterType="Integer" resultType="com.demo.po.CommodityStorage"> select commodity_id as commodityId, commodity_name as commodityName enter_date as enterDate,commodity_amount as commodityAmount, commodity_supplier as commoditySupplier from commodity_storage where commodity_amount <#{commodityAmount} </select> </mapper>
8.dao层负责实现Java应用程序到关系数据表的持久化操作,在com.demo.dao包下添加MyDemoDAO文件
MyDemoDAO.java
package com.demo.dao; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; 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 com.demo.po.CommodityStorage; import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List; public class MyDemoDAO { private SqlSession sqlSession; public MyDemoDAO() { //sqlsession实例初始化 try { InputStream ips = Resources.getResourceAsStream("mybatis-config.xml"); SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(ips); sqlSession = sessionFactory.openSession(); }catch (Exception e) { e.printStackTrace(); } } //插入商品库存 public void insertCustomer(CommodityStorage cs) { //第一个参数为映射文件CommodityStorageMapper.xml中的namespace加上<insert>节点的id //第二个参数为语句中的pojo实例 int rows= sqlSession.insert("com.demo.po.CommodityStorage.insertCommodity",cs); if(rows>0) { System.out.println("数据插入成功!"); }else { System.out.println("数据插入失败!"); } sqlSession.commit(); sqlSession.close(); } //更新商品库存 public void updateCustomer(CommodityStorage cs) { //第一个参数为映射文件CommodityStorageMapper.xml中的namespace加上<update>节点的id //第二个参数为语句中的pojo实例 int rows= sqlSession.update("com.demo.po.CommodityStorage.updateCommodity",cs); if(rows>0) { System.out.println("数据更新成功!"); }else { System.out.println("数据更新失败!"); } sqlSession.commit(); sqlSession.close(); } //删除商品库存 public void deleteCustomer(String name) { //第一个参数为映射文件CommodityStorageMapper.xml中的namespace加上<delete>节点的id //第二个参数为语句中的pojo实例 int rows= sqlSession.delete("com.demo.po.CommodityStorage.deleteCommodity",name); if(rows>0) { System.out.println("数据删除成功!"); }else { System.out.println("数据删除失败!"); } sqlSession.commit(); sqlSession.close(); } //检索单条商品库存 public void findCommodityById(String Commodityid) { //第一个参数为映射文件CommodityStorageMapper.xml中的namespace加上<select>节点的id //第二个参数为语句中的pojo实例 CommodityStorage cs1= sqlSession.selectOne("com.demo.po.CommodityStorage.findCommodityById",Commodityid); System.out.println(cs1.getCommodityId()+"\t"+cs1.getCommodityName()+"\t"+cs1.getCommodityAmount() +"\t"+cs1.getCommoditySupplier()+"\t"+cs1.getEnterDate()); sqlSession.close(); } //检索多条商品库存 public void findCommodityByAmount(Integer amount) { //第一个参数为映射文件CommodityStorageMapper.xml中的namespace加上<select>节点的id //第二个参数为语句中的pojo实例 List<CommodityStorage> list= sqlSession.selectList("com.demo.po.CommodityStorage.findCommodityByAmount",amount); for(int i=0;i<list.size();i++) { CommodityStorage cs1=list.get(i); System.out.println(cs1.getCommodityId()+"\t"+cs1.getCommodityName()+"\t"+cs1.getCommodityAmount() +"\t"+cs1.getCommoditySupplier()+"\t"+cs1.getEnterDate()); } sqlSession.close(); } public static void main(String[] args) { MyDemoDAO dao=null; CommodityStorage cs=null; //插入商品库存数据 /* dao=new MyDemoDAO(); cs=new CommodityStorage(); cs.setCommodityId("C010"); cs.setCommodityName("乒乓球"); cs.setCommoditySupplier("天利"); cs.setCommodityAmount(34); Date now=new Date(); cs.setEnterDate(now); dao.insertCustomer(cs); */ //修改商品库存数据 dao=new MyDemoDAO(); cs=new CommodityStorage(); cs.setCommoditySupplier("新丰慧"); cs.setCommodityAmount(180); dao.updateCustomer(cs); //删除商品库存数据 dao=new MyDemoDAO(); dao.deleteCustomer("口罩"); } }
9.调试报错
解决办法是mybatis包和MySQL的包版本不兼容导致,将mysql-connector-java-5.0.8-bin.jar更换为mysql-connector-java-5.1.34-bin.jar,运行成功
检查数据库中文乱码
解决办法是修改mybatis-config.xml文件中的数据库连接url如下:
<property name="url" value="jdbc:mysql://localhost:3306/my_db?useUnicode=true&characterEncoding=UTF-8"/>
转载文章链接已标明,如有侵权请告知。文章仅作为知识记忆所用,如有错误,敬请指正。