一.声明数据库的配置文件不同
mabatis:
<?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> <!-- 批量为pojo包下的所有类使用别名 --> <typeAliases> <package name="com.how2java.pojo"/> </typeAliases> <!-- 环境配置 --> <environments default="development"> <!-- 开发环境 --> <environment id="development"> <!-- 事务管理器 --> <!-- type为JDBC,通过类configuration知道,其为JdbcTransactionFactory.class类的别名 --> <transactionManager type="JDBC"/> <!-- 数据源 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="admin"/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/how2java/pojo/Category.xml"/> <mapper resource="com/how2java/pojo/Product.xml"/> <mapper resource="com/how2java/pojo/Order.xml"/> <mapper resource="com/how2java/pojo/OrderItem.xml"/> </mappers> </configuration>
hibernate:
<?xml version=‘1.0‘ encoding=‘utf-8‘?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 数据库连接的设置 --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8</property> <property name="connection.username">root</property> <property name="connection.password">admin</property> <!-- mysql的方言 --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 事务管理方式,一个线程对应一个事务 --> <property name="current_session_context_class">thread</property> <!-- 是否在控制台显示执行的sql语句 --> <property name="show_sql">true</property> <!-- 是否会自动更新数据库的表结构(不需要去创建表,因为hibernate会自动去创建表结构) --> <property name="hbm2ddl.auto">update</property> <!-- 表示hibernate会去识别Product这个实体类 --> <mapping resource="com/how2java/pojo/Product.hbm.xml" /> </session-factory> </hibernate-configuration>
二. 创建session时方式不同
mybatis:
package com.how2java; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; 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.how2java.pojo.Category; import com.how2java.pojo.Order; import com.how2java.pojo.OrderItem; import com.how2java.pojo.Product; /** * * @author luyurong * */ public class TestMybatis { public TestMybatis() { // TODO Auto-generated constructor stub } public static void main(String[] args) throws IOException { String resource="mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); // 根据配置文件得到SqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 根据SqlSessionFactory得到session SqlSession session = sqlSessionFactory.openSession(); // // 插入一个新的catgory // insertCategory(session); // // // 删除id为2的category // deleteCategory(session); // // 查询出所有的category // listAllCategory(session); // // 修改category // updateCategory(session); // 查询指定id的category // getCategory(session); // 列出所有category及其包含的product // listAllCategoryAndProduct(session); // // 列出所有product及其对应的category // listAllProductAndCategory(session); // 列出所有order listOrder(session); session.commit(); session.close(); } /** * 列出所有的category * @param session */ public static void listAllCategory(SqlSession session) { List<Category> cs = session.selectList("listCategory"); for (Category category : cs) { System.out.println(category.getName()); } } /** * 插入一个category * @param session */ public static void insertCategory(SqlSession session) { Category c = new Category(); c.setName("新增的category"); session.insert("addCategory",c); } /** * 删除一个category * @param session */ public static void deleteCategory(SqlSession session) { Category c = new Category(); c.setId(2); session.delete("deleteCategory",c); } /** * 根据id获取一个category * @param session */ public static void getCategory(SqlSession session) { Category c = session.selectOne("getCategory",3); System.out.println(c.getName()); } /** * 更新一个category * @param session */ public static void updateCategory(SqlSession session) { Category c = new Category(); c.setId(3); c.setName("hh"); session.update("updateCategory",c); } /** * 通过id和模糊查询的name列出category * @param session */ public static void listCategoryByIdAndName(SqlSession session) { Map<String,Object> params = new HashMap<>(); params.put("id", 1); params.put("name", "h"); List<Category> cs = session.selectList("listCategoryByIdAndName",params); for (Category category : cs) { System.out.println(category.getName()); } } /** * 列出所有的category包括category里的产品 * @param session */ public static void listAllCategoryAndProduct(SqlSession session) { List<Category> cs = session.selectList("listCategoryAndProduct"); for (Category category : cs) { System.out.println(category.getName()); System.out.println(category.toString()); List<Product> products = category.getProducts(); for (Product product : products) { System.out.println(product); } } } /** * 列出所有的product包括product里的category * @param session */ public static void listAllProductAndCategory(SqlSession session) { List<Product> ps = session.selectList("listProductAndCategory"); for (Product product : ps) { System.out.println(product); Category c = product.getCategory(); System.out.println(c); } } public static void listOrder(SqlSession session) { List<Order> os=session.selectList("listOrder"); for (Order order : os) { System.out.println(order.getCode()); List<OrderItem> orderItems = order.getOrderItems(); Iterator<OrderItem> it=orderItems.iterator(); while(it.hasNext()) { OrderItem oi=it.next(); System.out.format("\t%s\t%f\t%d%n", oi.getProduct().getName(),oi.getProduct().getPrice(),oi.getNumber()); } } } }
hibernate:
package com.how2java.test; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import com.how2java.pojo.Product; public class TestHibernate { public static void main(String[] args) { // 获取SessionFactory SessionFactory sf = new Configuration().configure().buildSessionFactory(); // 通过SessionFactory获取Session Session s = sf.openSession(); // 在Session的基础上开启一个事务 s.beginTransaction(); // 通过调用Session的save方法把对象保存到数据库 Product p = new Product(); p.setName("iphone7"); p.setPrice(7000.0f); s.save(p); // 提交事务 s.getTransaction().commit(); // 关闭session s.close(); // 关闭SessionFactory sf.close(); } }
三.每个类对象的xml文件格式不同
mybatis:
<?xml version="1.0" encoding="UTF-8"?> <!-- 注意:这里写的是mapper,而mybatis总配置里写的是config --> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!-- 指定命名空间 --> <mapper namespace="com.how2java.pojo"> <!-- 通过resultMap将数据取出来放到对应的对象属性里 --> <resultMap type="product" id="productBean"> <id column="pid" property="id"/> <result column="pname" property="name"/> <result column="price" property="price"/> <!-- 多对一的关系 --> <!-- property指的是属性名称,javaType指的是属性的类型 --> <association property="category" javaType="category"> <id column="cid" property="id"/> <result column="cname" property="name"/> </association> </resultMap> <!-- 根据id查询Product,关联将Category查出来 --> <select id="listProductAndCategory" resultMap="productBean"> select p.*,c.*,p.id ‘pid‘,c.id ‘cid‘,p.name ‘pname‘,c.name ‘cname‘ from category_ c right join product_ p on c.id=p.cid </select> <!-- 根据指定id查询Product,关联将Category查出来 --> <select id="getProductAndCategory" resultMap="productBean"> select p.*,c.*,p.id ‘pid‘,c.id ‘cid‘,p.name ‘pname‘,c.name ‘cname‘ from category_ c right join product_ p on c.id=p.cid where p.id=#{id} </select> <!-- 多条件查询product --> <select id="listProduct" resultType="product"> select * from product_ <where> <if test="name!=null"> and name like concat(‘%‘,#{name},‘%‘) </if> <if test="price!=null and price!=0"> and price>#{price} </if> </where> </select> </mapper>
hibernate:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <!-- package指的是Product类的位置 --> <hibernate-mapping package="com.how2java.pojo"> <!-- 指明类和数据库的映射 --> <class name="Product" table="product_"> <!-- 属性id,映射表里的id --> <id name="id" column="id"> <!-- id的自增方式采用数据库的本地方式 --> <generator class="native"></generator> </id> <!-- 没有写column,则表明表里的名字也是name --> <property name="name"/> <property name="price"/> </class> </hibernate-mapping>