mybatis註解式的增刪改查、一對多、多對一、多對多
阿新 • • 發佈:2018-11-09
目錄
一、專案資料庫表和資料的截圖。
也可自己錄入資料,測試關聯查詢和增刪改查。
二、maven專案所需依賴。
<dependencies> <!--資料庫連線驅動--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies>
三、mybatis配置檔案。
這裡掃描得事mapper介面了,不再是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> <!--設定別名--> <package name="com.byh.pojo"/> </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://localhost:3306/dbmybatis?characterEncoding=UTF-8"/> <property name="username" value="root"/> <property name="password" value="admin"/> </dataSource> </environment> </environments> <!--掃描mapper檔案--> <mappers> <mapper class="com.byh.mapper.CategoryMapper"/> <mapper class="com.byh.mapper.ProductMapper"/> <mapper class="com.byh.mapper.OrderMapper"/> <mapper class="com.byh.mapper.OrderItemMapper"/> </mappers> </configuration>
四、增刪改查。
只需把xml中的sql語句放在方法上就可以了。
@Insert("insert into category ( name ) values (#{name})") void addCategory(Category category); @Delete("delete from category where id= #{id}") void delCategory(Category category); @Update("update category set name=#{name} where id=#{id}") void updateCategory(Category category); @Select("select * from category where id= #{id}") Category getCategoryById(int id);
五、一對多
查詢分類的時候,查詢分類下的商品:
1.CategoryMapper介面中:(@Results 通過@Result和@Many中呼叫ProductMapper.productListByCid()方法相結合,來獲取一對多關係)
@Select("select * from category")
@Results({
@Result(column = "id",property = "id"),
@Result(property = "products",javaType = List.class,column = "id",//column = "id":表示拿著category表中的主鍵id,去查詢product表
many = @Many(select = "com.byh.mapper.ProductMapper.productListByCid"))
})
List<Category> listCategory();
2.ProductMapper介面中:(根據分類id獲取產品集合)
@Select("select * from product where cid=#{cid}")
List<Product> productListByCid(int cid);
3.測試:最後直接呼叫listCategory();方法即可查出分類列表,以及每個分類下的所有商品列表。
六、多對一
1.CategoryMapper介面中新增:
@Select("select * from category where id= #{id}")
Category getCategoryById(int id);
2.ProductMapper介面中新增:
@Select("select * from product")
@Results({
@Result(property="category",column="cid",[email protected](select="com.byh.mapper.CategoryMapper.getCategoryById"))
})
List<Product> list();
3.測試:直接呼叫list();方法即可查詢商品列表,以及每個列表所屬分類。
七、多對多
1.ProductMapper介面中新增:
@Select("select * from product where id = #{id}")
public Product getProductById(int id);
2.OrderItemMapper介面新增:
//根據oid查詢訂單下的訂單項列表 在根據pid查詢對應product
//查詢單個商品實體,然後給orderitem實體中的product屬性設定值,表示訂單項中所屬的商品為具體的什麼。
@Select(" select * from order_item where oid = #{oid}")
@Results({
@Result(property="product",column="pid",[email protected](select="com.byh.mapper.ProductMapper.getProductById"))
})
List<OrderItem> listByOrder(int oid);
3.OrderMapper介面中新增:給order實體中的orderitems屬性設定值,通過order的id呼叫OrderItemMapper中的方法listByOrder(int oid)完成。這樣就是給每個訂單關聯相關的訂單項。
@Select("select * from `order`")
@Results({
@Result(column = "id",property = "id"), //這裡的javaType應該是屬性的型別
@Result(property = "orderItems",column = "id",javaType = List.class,
many = @Many(select = "com.byh.mapper.OrderItemMapper.listByOrder"))
})
List<Order> orderList();
4.測試:呼叫orderList();方法即可檢視訂單列表,以及訂單列表下有哪些訂單項,訂單項中又有哪些商品。
八、所有測試的一個總體的測試類:
import com.byh.mapper.CategoryMapper;
import com.byh.mapper.OrderMapper;
import com.byh.mapper.ProductMapper;
import com.byh.pojo.Category;
import com.byh.pojo.Order;
import com.byh.pojo.OrderItem;
import com.byh.pojo.Product;
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class Demo1 {
private SqlSession session ;
private CategoryMapper categoryMapper;
private ProductMapper productMapper;
private OrderMapper orderMapper;
@Before
public void bef() throws IOException {
//mybatis的配置檔案
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//構建sqlSession的工廠
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//建立能執行對映檔案中sql的sqlSession
session=sqlSessionFactory.openSession();
categoryMapper = session.getMapper(CategoryMapper.class);
productMapper = session.getMapper(ProductMapper.class);
orderMapper = session.getMapper(OrderMapper.class);
}
/**
* 關閉SqlSession的方法
* @param session
*/
public void close(SqlSession session){
session.commit();
session.close();
}
@Test //查詢所有
public void findAll() throws IOException {
List<Category> cs=categoryMapper.listCategory();
for (Category c : cs) {
System.out.println(c.getName()+c.getProducts());
}
}
@Test //增加
public void add() throws IOException {
Category c = new Category();
c.setName("我是新增的分類");
categoryMapper.addCategory(c);
findAll();
//提交和關閉,呼叫自定義方法
close(session);
}
@Test //刪除
public void del() throws IOException {
findAll();
System.out.println("------------刪除後-----------");
Category c = new Category();
c.setId(5);
categoryMapper.delCategory(c);//這裡的5是一個數據庫存在的id
findAll();
close(session);
}
@Test //更新
public void update() throws IOException {
findAll();
System.out.println("------------更新後-----------");
Category c = categoryMapper.getCategoryById(2);//查詢單個物件
c.setName("分類2被修改了a");
categoryMapper.updateCategory(c);
findAll();
close(session);
}
@Test
public void mToOne(){
List<Product> list = productMapper.list();
for (Product p:list){
System.out.println(p);
}
}
@Test
public void MtoM(){
List<Order> list = orderMapper.orderList();
for (Order o:list){
System.out.println(o.getCode());
List<OrderItem> ois= o.getOrderItems();
if(null!=ois){
for (OrderItem oi : ois) {
System.out.format("%d\t%s\t%f\t%d%n",oi.getId(), oi.getProduct().getName(),oi.getProduct().getPrice(),oi.getNumber());
}
}
}
}
}
九、專案主體結構圖: