MyBatis入门及CRUD
MyBatis是一个ORM的数据操作框架
myBatis的基本配置
首先创建一个普通 java项目,引入响应jar包,然后引入mybatis的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> <!--链接properties-->
<properties resource="jdbc.properties" /> <!--设置他的别名 设为包的话别名就是包下面的类名-->
<typeAliases>
<package name="cn.newsoft.domain"></package>
</typeAliases> <!--配置环境们
default:默认使用的哪个环境
-->
<environments default="development"> <!--配置单个环境-->
<environment id="development">
<!--配置事务,有这两个属性
JDBC:使用JDBC的默认事务功能
MANAGED:表示没有事务
-->
<transactionManager type="JDBC"/>
<!--配置连接池-->
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!--引入写sql语句的xml文件-->
<mappers>
<mapper resource="cn/newsoft/test/productMapper.xml"/>
</mappers>
</configuration>
配置链接数据库的properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///自己的数据库名
jdbc.username=自己用户名
jdbc.password=数据库密码
然后写好domain对象,然后在测试类写一个xml,这个xml中就是定义自己的sql语句,可以采用别名的方式,解决全限名的问题
<?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="cn.newsoft.test.productMapper">
<!--parametertype表示传入参数的类型
resulttype表示每一条数据传出时的类型
-->
当damian中数据库字段和domain中的不对应时就可以用这个方法来统一字段
<resultMap id="prductMap" type="Product">
<result column="dir_id" property="dirId"></result> </resultMap> <!--查询一个-->
<select id="findone" parameterType="long" resultType="Product">
select * from product where id = #{id}
</select> <!--查询全部-->
<select id="findAll" resultMap="prductMap">
select * from product
</select> <!--添加操作-->
<insert id="insert" parameterType="Product">
insert into product(productName,dir_id,salePrice,supplier,brand,cutoff,costPrice)
values (#{productName},#{dirId},#{salePrice},#{supplier},#{brand},#{cutoff},#{costPrice})
</insert> <!--修改操作-->
<update id="update" parameterType="Product" >
update product set productName=#{productName},dir_id=#{dirId},salePrice=#{salePrice},
supplier=#{supplier},brand=#{brand},cutoff=#{cutoff},costPrice=#{costPrice} where id=#{id} </update>
<!--删除一个-->
<delete id="delete" parameterType="long">
delete from product where id=#{id}
</delete>
</mapper>
然后我们定义一个工具类用来获取sqlsession对象
package cn.newsoft.util; 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 java.io.IOException;
import java.io.Reader; public class MybatisUtil {
private static SqlSessionFactory build;
static {
try {
Reader resource = Resources.getResourceAsReader("mybatis.xml");
build = new SqlSessionFactoryBuilder().build(resource); } catch (IOException e) {
e.printStackTrace();
}
} public static SqlSession gtSession(){
SqlSession sqlSession = build.openSession();
return sqlSession; } }
dao层为
package cn.newsoft.dao.impl; import cn.newsoft.dao.IproductDao;
import cn.newsoft.domain.Product;
import cn.newsoft.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession; import java.util.List; public class ProductImpl implements IproductDao { @Override
public void save(Product product) {
SqlSession sqlSession = MybatisUtil.gtSession();
sqlSession.insert("cn.newsoft.test.productMapper.insert", product); }
//cn.newsoft.test.productMapper.update"为命名空间的全限定名 update执行的方法名称
@Override
public void update(Product product) {
SqlSession sqlSession = MybatisUtil.gtSession();
sqlSession.update("cn.newsoft.test.productMapper.update", product);
} @Override
public void delete(Long id) {
SqlSession sqlSession = MybatisUtil.gtSession();
sqlSession.delete("cn.newsoft.test.productMapper.delete", id);
} @Override
public Product findone(Long id) {
SqlSession sqlSession = MybatisUtil.gtSession();
Product o = (Product)sqlSession.selectOne("cn.newsoft.test.productMapper.findone",id);
return o;
} @Override
public List<Product> findAll() {
SqlSession sqlSession = MybatisUtil.gtSession();
List<Product> list = sqlSession.selectList("cn.newsoft.test.productMapper.findAll");
return list;
}
}
然后在测试类中进行测试
package cn.newsoft.test; import cn.newsoft.dao.impl.ProductImpl;
import cn.newsoft.domain.Product;
import cn.newsoft.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test; import java.util.List; public class IproductDaoTest { ProductImpl products = new ProductImpl();
@Test
public void save() { Product product = new Product();
product.setProductName("sss");
product.setSupplier("changcu");
products.save(product); } @Test
public void update() {
Product findone = products.findone(22L);
findone.setProductName("李逵");
products.update(findone);
} @Test
public void delete() {
products.delete(21L);
} @Test
public void findone() { Product findone = products.findone(1L);
System.out.println(findone);
} @Test
public void findAll() {
List<Product> all = products.findAll();
all.forEach(e ->
System.out.println(e));
}
}
这样就完成他的CRUD,
日志管理
引入jar包
#log4j.properties(日志文件:)
# ERROR错误的日志 WARN:警告 INFO:普通信息 DEBUG:调试日志 TRACE:日志
log4j.rootLogger=ERROR, stdout
#log4j.rootLogger=NONE
#把左边包名改成你自己的包名
log4j.logger.cn.itsource=TRACE # 日志打印到控制台中
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
# 日志打印的一种格式(可以灵活地指定布局模式)
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# 日志打印的格式是什么样子的 %d:日期 %p:优先级 %c:类的全名 %m:输出的结果 %n:换行
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
MyBatis入门及CRUD的更多相关文章
- mybatis入门,CRUD,万能Map,模糊查询
第一个Mybatis程序 核心配置文件mybatis-config.xml <?xml version="1.0" encoding="UTF-8" ?& ...
- MyBatis入门学习教程-使用MyBatis对表执行CRUD操作
上一篇MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对use ...
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作(转载)
本文转载自:http://www.cnblogs.com/jpf-java/p/6013540.html 上一篇博文MyBatis学习总结(一)--MyBatis快速入门中我们讲了如何使用Mybati ...
- MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作
上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据,算是对MyBatis有一个初步的入门了,今天讲解一下如何使用MyBatis对u ...
- 【转】MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作
[转]MyBatis学习总结(二)——使用MyBatis对表执行CRUD操作 上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用Mybatis查询users表中的数据, ...
- Mybatis入门看这一篇就够了
什么是MyBatis MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为 ...
- 【转载】 mybatis入门系列四之动态SQL
mybatis 详解(五)------动态SQL 目录 1.动态SQL:if 语句 2.动态SQL:if+where 语句 3.动态SQL:if+set 语句 4.动态SQL:choose(when, ...
- MyBatis学习笔记(二)——使用MyBatis对表执行CRUD操作
转自孤傲苍狼的博客:http://www.cnblogs.com/xdp-gacl/p/4262895.html 上一篇博文MyBatis学习总结(一)——MyBatis快速入门中我们讲了如何使用My ...
- Mybatis系列(一):Mybatis入门
一.Mybatis是什么 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改 ...
随机推荐
- NotePad++替换行前、行后空格,替换空行
用 Notepad++ 打开,把每一个将要放在表中单元格的内容放一行(注: ^ 代表行首 $ 代表行尾) 去除行尾空格和空白行:按CTRL+H 选择正则表达式– 查找目标:\s+$ 替换为空 去除行首 ...
- mongoTemplate.aggregate()聚合查询
一.概述 1. 聚合的表达式 MongoDB中聚合(aggregate)主要用于处理数据(诸如统计平均值,求和等),并返回计算后的数据结果.有点类似sql语句中的 count(*). 下表展示了一些聚 ...
- java.lang.VerifyError: Inconsistent stackmap frames at branch target 81
java项目中有如下代码: @RequestMapping(value = "/getMxList") @ResponseBody public Map<String, Ob ...
- Redis AOF文件
[Redis AOF文件] 1.关于AOF AOF 持久化记录服务器执行的所有写操作命令,并在服务器启动时,通过重新执行这些命令来还原数据集. AOF 文件中的命令全部以 Redis 协议的格式来保存 ...
- java并发特性:原子性、可见性、有序性
要想并发程序正确地执行,必须要保证原子性.可见性以及有序性.只要有一个没有被保证,就有可能会导致程序运行不正确. 1.原子性(Atomicity) 原子性是指在一个操作中就是cpu不可以在中途暂停然后 ...
- java普通类如何调用Spring的Service层?
首先在Service层上面添加 @Service("myService") 然后,在main方法中调用,String[]中为配置文件,如下所示: ApplicationContex ...
- 利率计算v4.0--测试--软件工程
利率计算v4.0--测试 package Test; import Model.Interest; import Service.CompoundInterestService; import Ser ...
- BZOJ 1001 狼抓兔子 (最小割转化成最短路)
1001: [BeiJing2006]狼抓兔子 Time Limit: 15 Sec Memory Limit: 162 MBSubmit: 27715 Solved: 7134[Submit][ ...
- CodeForces 681A A Good Contest (水题)
题意:给定 n 个人和before, after的分数,让你找 before 的分数大于等于2400并且before 小于 after. 析:看完题意就知道怎么算了吧..不用说了 #include & ...
- Word直接发布新浪博客(以Word 2010为例)
目前大部分的博客作者在用Word写博客这件事情上都会遇到以下3个痛点: 1.所有博客平台关闭了文档发布接口,用户无法使用Word,Windows Live Writer等工具来发布博客.使用Word写 ...