主頁 > 後端開發 > jdbc增刪改查操作,封裝工具類,實作泛型介面無限套娃

jdbc增刪改查操作,封裝工具類,實作泛型介面無限套娃

2021-12-21 08:05:01 後端開發

jdbc基本操作:

(1)加載并注冊資料庫驅動,

(2)通過DriverManager獲取資料庫連接,

(3)通過Connection物件獲取Statement物件,

(4)使用Statement執行SQL陳述句,

(5)操作ResultSet結果集,

(6)關閉連接,釋放資源,在這里插入圖片描述

資料庫的操作其實都差不多,我們可以把相同的內容寫成方法、工具類,這樣可以極大地減小耦合度,也方便我們以后的套用,可以無限套娃,

這里用的是mysql資料庫

下面看看具體操作

第一步先建資料表吧

good商品表

CREATE TABLE `good` (
  `id` int(10) NOT NULL AUTO_INCREMENT COMMENT '商品id',
  `name` varchar(20) NOT NULL COMMENT '商品名稱',
  `price` float NOT NULL COMMENT '商品價格',
  `stock` int(10) DEFAULT NULL COMMENT '商品庫存',
  `count` int(10) unsigned zerofill DEFAULT '0000000000' COMMENT '訂單量',
  `imgUrl` longtext CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT '商品圖片',
  `type` varchar(20) DEFAULT NULL COMMENT '商品型別',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=111121 DEFAULT CHARSET=utf8

user用戶表

CREATE TABLE `user` (
  `id` int(10) NOT NULL AUTO_INCREMENT COMMENT '用戶id',
  `name` varchar(20) NOT NULL COMMENT '用戶名',
  `password` varchar(16) NOT NULL COMMENT '密碼',
  `mobile` int(13) DEFAULT NULL COMMENT '電話號碼',
  `qq` int(12) DEFAULT NULL COMMENT 'QQ號碼',
  `signinTime` datetime DEFAULT NULL COMMENT '注冊時間',
  `count` int(10) DEFAULT NULL COMMENT '購買次數',
  `address` varchar(255) DEFAULT NULL COMMENT '用戶地址',
  `role` varchar(10) DEFAULT NULL COMMENT '用戶角色',
  `email` varchar(255) DEFAULT NULL COMMENT '用戶郵箱',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11113 DEFAULT CHARSET=utf8

底層都是一樣的,可以寫個工具類
.

DBUtil.java工具類


package com.xmj.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
	private final static String DRIVER = "com.mysql.cj.jdbc.Driver";
	private final static String URL ="jdbc:mysql://127.0.0.1:3306/你的資料庫名?useSSL=false&serverTimezone=UTC";
	private final static String USERNAME = "用戶名";
	private final static String PASSWORD = "密碼";
	public static Connection connection = null;
  	public static PreparedStatement pstmt = null;
  	public static ResultSet rs = null;
  	public static Connection getConnection() throws ClassNotFoundException, SQLException {
  		Class.forName(DRIVER);
		return DriverManager.getConnection(URL,USERNAME,PASSWORD);
  	}
  	
  	public static PreparedStatement createPreparedStatement(String sql,Object[] params) throws SQLException, ClassNotFoundException {
  		pstmt = getConnection().prepareStatement(sql);
		if(params!=null)
		for(int i=0;i<params.length;i++) {
			pstmt.setObject(i+1, params[i]);
		}
	return pstmt;
  	}
  	
	//查詢總數
  	public static int getTotalCount(String sql) {
  		int count =  -1;	
  		 try {
  			 pstmt =  createPreparedStatement(sql, null);
  			 ResultSet rs =  pstmt.executeQuery();
  			 
  			 if(rs.next()) { 	
  				count = rs.getInt(1); 
  			 }
  		 
  		 
  		 }catch (ClassCastException e) {
			// TODO: handle exception
  			 e.printStackTrace();
		}catch (SQLException e) {
			// TODO: handle exception
 			 e.printStackTrace();
		}catch (Exception e) {
			// TODO: handle exception
 			 e.printStackTrace();
		}finally {
			closeAll(rs, pstmt, connection);
		}
		return count;
  	}
  	
  	
  //增刪改
  	public static boolean excuteUpdate(String sql,Object[] params) throws ClassNotFoundException {
  		
  		try {
  			pstmt = createPreparedStatement(sql,params);
  			int count = pstmt.executeUpdate();
  			if(count>0) return true;
  			else return false;
  			
  		} catch (SQLException e) {
  			// TODO Auto-generated catch block
  			e.printStackTrace();
  			return false;
  		}catch (Exception e) {
  			// TODO: handle exception
  			e.printStackTrace();
  			return false;
  		}finally{
  			closeAll(null,pstmt,connection);
  		}
  	}
  	//查
  	public static ResultSet executeQuery(String sql,Object[] params) {
  		try {
  			pstmt = createPreparedStatement(sql,params);
  			rs = pstmt.executeQuery();
  			return rs;
  		} catch (ClassNotFoundException e) {
  			// TODO Auto-generated catch block
  			e.printStackTrace();
  			return null;
  		} catch (SQLException e) {
  			// TODO Auto-generated catch block
  			e.printStackTrace();
  			return null;
  		}catch (Exception e) {
  			// TODO: handle exception
  			e.printStackTrace();
  			return null;
  		}
  		finally{
  			closeAll(null,null,connection);
  		}
  		
  	}
  	public static void closeAll(ResultSet rs ,Statement stmt,Connection connection) {
  		try {
  			if(rs!=null)rs.close();
//  			if(pstmt!=null)pstmt.close();
  			if(connection!=null)connection.close();
  		} catch (SQLException e) {
  			// TODO Auto-generated catch block
  			e.printStackTrace();
  		}
  	}
}

Good物體類


package com.xmj.entity;

public class Good {
		private Integer id;
	    private String name;
	    private Float price;
	    private Integer stock;
	    private Integer count;
	    private String imgUrl;
	    private String type;
		/**
		 * @return the id
		 */
		public Integer getId() {
			return id;
		}
		public Good(String name, Float price, Integer stock, Integer count, String imgUrl, String type) {
			super();
			this.name = name;
			this.price = price;
			this.stock = stock;
			this.count = count;
			this.imgUrl = imgUrl;
			this.type = type;
		}
		/**
		 * @param id the id to set
		 */
		public void setId(Integer id) {
			this.id = id;
		}
		/**
		 * @return the name
		 */
		public String getName() {
			return name;
		}
		/**
		 * @param name the name to set
		 */
		public void setName(String name) {
			this.name = name;
		}
		/**
		 * @return the price
		 */
		public Float getPrice() {
			return price;
		}
		/**
		 * @param price the price to set
		 */
		public void setPrice(Float price) {
			this.price = price;
		}
		/**
		 * @return the stock
		 */
		public Integer getStock() {
			return stock;
		}
		/**
		 * @param stock the stock to set
		 */
		public void setStock(Integer stock) {
			this.stock = stock;
		}
		/**
		 * @return the count
		 */
		public Integer getCount() {
			return count;
		}
		/**
		 * @param count the count to set
		 */
		public void setCount(Integer count) {
			this.count = count;
		}
		/**
		 * @return the imgUrl
		 */
		public String getImgUrl() {
			return imgUrl;
		}
		/**
		 * @param imgUrl the imgUrl to set
		 */
		public void setImgUrl(String imgUrl) {
			this.imgUrl = imgUrl;
		}
		/**
		 * @return the type
		 */
		public String getType() {
			return type;
		}
		/**
		 * @param type the type to set
		 */
		public void setType(String type) {
			this.type = type;
		}
		public Good(Integer id, String name, Float price, Integer stock, Integer count, String imgUrl, String type) {
			super();
			this.id = id;
			this.name = name;
			this.price = price;
			this.stock = stock;
			this.count = count;
			this.imgUrl = imgUrl;
			this.type = type;
		}
		public Good() {
			super();
		}
	    
}

user物體類


package com.xmj.entity;

import java.util.Date;

public class User {
	 	private Integer id;
	    private String name;
	    private String password;
	    private Integer mobile;
	    private String role;
	    private Integer QQ;
	    private String email;
	    private Date signinTime;
	    private Integer count;
	    private String address;
		/**
		 * @return the id
		 */
		public Integer getId() {
			return id;
		}
		/**
		 * @param id the id to set
		 */
		public void setId(Integer id) {
			this.id = id;
		}
		/**
		 * @return the name
		 */
		public String getName() {
			return name;
		}
		/**
		 * @param name the name to set
		 */
		public void setName(String name) {
			this.name = name;
		}
		/**
		 * @return the password
		 */
		public String getPassword() {
			return password;
		}
		/**
		 * @param password the password to set
		 */
		public void setPassword(String password) {
			this.password = password;
		}
		/**
		 * @return the mobile
		 */
		public Integer getMobile() {
			return mobile;
		}
		/**
		 * @param mobile the mobile to set
		 */
		public void setMobile(Integer mobile) {
			this.mobile = mobile;
		}
		/**
		 * @return the role
		 */
		public String getRole() {
			return role;
		}
		/**
		 * @param role the role to set
		 */
		public void setRole(String role) {
			this.role = role;
		}
		/**
		 * @return the qQ
		 */
		public Integer getQQ() {
			return QQ;
		}
		/**
		 * @param qQ the qQ to set
		 */
		public void setQQ(Integer qQ) {
			QQ = qQ;
		}
		/**
		 * @return the email
		 */
		public String getEmail() {
			return email;
		}
		/**
		 * @param email the email to set
		 */
		public void setEmail(String email) {
			this.email = email;
		}
		/**
		 * @return the signinTime
		 */
		public Date getSigninTime() {
			return signinTime;
		}
		/**
		 * @param signinTime the signinTime to set
		 */
		public void setSigninTime(Date signinTime) {
			this.signinTime = signinTime;
		}
		/**
		 * @return the count
		 */
		public Integer getCount() {
			return count;
		}
		/**
		 * @param count the count to set
		 */
		public void setCount(Integer count) {
			this.count = count;
		}
		/**
		 * @return the address
		 */
		public String getAddress() {
			return address;
		}
		/**
		 * @param address the address to set
		 */
		public void setAddress(String address) {
			this.address = address;
		}
		public User(Integer id, String name, String password, Integer mobile, String role, Integer qQ, String email,
				Date signinTime, Integer count, String address) {
			super();
			this.id = id;
			this.name = name;
			this.password = password;
			this.mobile = mobile;
			this.role = role;
			QQ = qQ;
			this.email = email;
			this.signinTime = signinTime;
			this.count = count;
			this.address = address;
		}
		public User(String name, String password, Integer mobile, String role, Integer qQ, String email,
				Date signinTime, Integer count, String address) {
			super();
			this.name = name;
			this.password = password;
			this.mobile = mobile;
			this.role = role;
			QQ = qQ;
			this.email = email;
			this.signinTime = signinTime;
			this.count = count;
			this.address = address;
		}
		
	   
}

泛型的好處就是,我們不用定義型別,讓你的代碼更通用,比如我們需要回傳型別是一個User類和Good類,不使用泛型就需要寫兩個方法,如果使用泛型,就只需要用T來泛指未知類,在我們呼叫的時候,直接用我們需要的類就可以了,

IMapper.java泛型介面


package com.xmj.mapper;

import java.sql.ResultSet;
import java.util.List;

import com.xmj.entity.DataVO;
import com.xmj.entity.Good;
import com.xmj.entity.Order;
import com.xmj.entity.User;

public interface IMapper<T> {
		//查總數
		public int getTotalCount();
		//判斷是否存在
		public boolean isExist(int id) ;
		//增
		public boolean add(T t);
		//改
		public boolean updateById(int id, T good) throws ClassNotFoundException;
		//刪
		public boolean deleteById(int sno) ;
		//查全部
		public List<T> queryAll();
		//查,限制頁數	
		public List<T> queryByPage(int currentPage, int pageSize);
		//根據id查
		public T queryById(int id);
		
}

GoodMapper進行持久化操作,實作IMapper介面,然后實作介面的方法

GoodMapper持久化層

package com.xmj.mapper;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.xmj.entity.DataVO;
import com.xmj.entity.Good;
import com.xmj.entity.Order;
import com.xmj.util.DBUtil;


public class GoodMapper implements IMapper<Good>{

	@Override
	public int getTotalCount() {
		String sql = "select count(*) from good;";
		return DBUtil.getTotalCount(sql);
	}

	@Override
	public boolean isExist(int id) {
		return queryById(id)!=null?true:false;
	}

	@Override
	public boolean add(Good good) {
		String sql = "insert into good(name,price,stock,count,imgUrl,type)values(?,?,?,?,?,?)";
		Object[] params = {good.getName(),good.getPrice(),good.getStock(),good.getCount(),good.getImgUrl(),good.getType()};
		try {
			return DBUtil.excuteUpdate(sql, params);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	@Override
	public boolean updateById(int id, Good good) throws ClassNotFoundException {
		String sql = "update good set name=?,price=?,stock=?,count=?,imgUrl=?,type=? where id=?";
		Object[] params = {good.getName(),good.getPrice(),good.getStock(),good.getCount(),good.getImgUrl(),good.getType(),id};
		return DBUtil.excuteUpdate(sql, params);
	}

	@Override
	public boolean deleteById(int id) {
		String sql = "delete from good where id=?";
		Object[] params = {id};
		try {
			return DBUtil.excuteUpdate(sql, params);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public Good queryById(int id) {
		PreparedStatement pstmt = null;
		Good good = null;
//		List<Good> goods = new ArrayList<>();
		ResultSet rs = null;
		try {
			String sql = "select * from good where id="+id;
			rs = DBUtil.executeQuery(sql, null);
			if(rs.next()) {
				int theid = rs.getInt("id");
				String name = rs.getString("name");
				Float price = rs.getFloat("price");
				int count = rs.getInt("count");
				int stock = rs.getInt("stock");
				String imgUrl = rs.getString("imgUrl");
				String type = rs.getString("type");
				good = new Good(theid,name,price,stock,count,imgUrl,type);
//				goods.add(good);
			}
			return good;
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}finally{
			DBUtil.closeAll(rs, pstmt,DBUtil.connection);
		}
	}

	@Override
	public List<Good> queryAll() {
		PreparedStatement pstmt = null;
		Good good = null;
		List<Good> goods = new ArrayList<>();
		ResultSet rs = null;
		try {
			String sql = "select * from good";
			rs = DBUtil.executeQuery(sql, null);
			while(rs.next()) {
				int id = rs.getInt("id");
				String name = rs.getString("name");
				Float price = rs.getFloat("price");
				int count = rs.getInt("count");
				int stock = rs.getInt("stock");
				String imgUrl = rs.getString("imgUrl");
				String type = rs.getString("type");
				good = new Good(id,name,price,stock,count,imgUrl,type);
				goods.add(good);
			}
			return goods;
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}finally{
			DBUtil.closeAll(null, DBUtil.pstmt,DBUtil.connection);
		}
	}

	@Override
	public List<Good> queryByPage(int currentPage, int pageSize) {
		String sql = "select * from good limit "+currentPage*pageSize+","+pageSize+";";
		Object[] params = {currentPage*pageSize,(currentPage-1)*pageSize+1};
		ResultSet rs  =  DBUtil.executeQuery(sql, params);
		List<Good> goods = new ArrayList<>();
		try {
			while(rs.next()) {
				Good good = new Good(rs.getInt("id"),rs.getString("name"),rs.getFloat("price"),rs.getInt("stock"),rs.getInt("count"),rs.getString("imgUrl"),rs.getString("type"));
				goods.add(good);
			}
		} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
 		return goods;
	}
}


GoodMapper進行持久化操作,同樣實作IMapper介面的方法,這時候你會發現,可以直接把上面的GoodMappr實作的方法復制粘貼過來,稍微修改一下就可以了,這樣是不是提高了效率呢

UserMapper持久化層

package com.xmj.mapper;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.xmj.entity.DataVO;
import com.xmj.entity.User;
import com.xmj.util.DBUtil;

public class UserMapper implements IMapper<User>{
	    
	@Override
	public int getTotalCount() {
		String sql = "select count(*) from user;";
		return DBUtil.getTotalCount(sql);
	}

	@Override
	public boolean isExist(int id) {
		return queryById(id)!=null?true:false;
	}

	@Override
	public boolean add(User user) {
		String sql = "insert into user(name,password,mobile,qq,signinTime,count,address,role,email)values(?,?,?,?,?,?,?,?,?)";
		Object[] params = {user.getName(),user.getPassword(),user.getMobile(),user.getQQ(),user.getSigninTime(),user.getCount(),user.getAddress(),user.getRole(),user.getEmail()};
		try {
			return DBUtil.excuteUpdate(sql, params);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	@Override
	public boolean updateById(int id, User user) throws ClassNotFoundException {
		String sql = "update user set name=?,password=?,mobile=?,qq=?,signinTime=?,count=?,address=?,role=?,email=? where id=?";
		Object[] params = {user.getName(),user.getPassword(),user.getMobile(),user.getQQ(),user.getSigninTime(),user.getCount(),user.getAddress(),user.getRole(),user.getEmail(),id};
		return DBUtil.excuteUpdate(sql, params);
	}

	@Override
	public boolean deleteById(int id) {
		String sql = "delete from user where id=?";
		Object[] params = {id};
		try {
			return DBUtil.excuteUpdate(sql, params);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public User queryById(int id) {
		PreparedStatement pstmt = null;
		User user = null;
//		List<Good> goods = new ArrayList<>();
		ResultSet rs = null;
		try {
			String sql = "select * from user where id="+id;
			rs = DBUtil.executeQuery(sql, null);
			if(rs.next()) {
				String name = rs.getString("name");
				String password = rs.getString("password");
				int mobile = rs.getInt("mobile");
				int qq = rs.getInt("qq");
				Date signinTime = rs.getDate("signinTime");
				Integer count = rs.getInt("count");
				String address = rs.getString("address");
				String role = rs.getString("role");
				String email = rs.getString("email");
				user = new User(id,name,password,mobile,role,qq,email,signinTime,count,address);
//				goods.add(good);
			}
			return user;
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}finally{
			DBUtil.closeAll(rs, pstmt,DBUtil.connection);
		}
	}

	@Override
	public List<User> queryAll() {
		PreparedStatement pstmt = null;
		User user = null;
		List<User> users = new ArrayList<>();
		ResultSet rs = null;
		try {
			String sql = "select * from user";
			rs = DBUtil.executeQuery(sql, null);
			while(rs.next()) {
				int id = rs.getInt("id");
				String name = rs.getString("name");
				String password = rs.getString("password");
				int mobile = rs.getInt("mobile");
				int qq = rs.getInt("qq");
				Date signinTime = rs.getDate("signinTime");
				Integer count = rs.getInt("count");
				String address = rs.getString("address");
				String role = rs.getString("role");
				String email = rs.getString("email");
				user = new User(id,name,password,mobile,role,qq,email,signinTime,count,address);
				users.add(user);
			}
			return users;
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return null;
		}finally{
			DBUtil.closeAll(null, DBUtil.pstmt,DBUtil.connection);
		}
	}

	@Override
	public List<User> queryByPage(int currentPage, int pageSize) {
		String sql = "select * from user limit "+currentPage*pageSize+","+pageSize+";";
		Object[] params = {currentPage*pageSize,(currentPage-1)*pageSize+1};
		ResultSet rs  =  DBUtil.executeQuery(sql, params);
		List<User> users = new ArrayList<>();
		try {
			while(rs.next()) {
				User user = new User(rs.getInt("id"),rs.getString("name"),rs.getString("password"),rs.getInt("mobile"),rs.getString("role"),rs.getInt("qq"),rs.getString("email"),rs.getDate("signinTime"),rs.getInt("count"),rs.getString("address"));
				users.add(user);
			}
		} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
 		return users;
	}
 }


接下來就是呼叫了,先寫個業務層吧,如果要用到Layui,就需要按指定格式回傳資料,所以在分頁查詢封裝了一下資料,這個就按你自己不同的需求來實作吧,

GoodService業務層


package com.xmj.service;

import java.util.List;

import com.xmj.entity.DataVO;
import com.xmj.entity.Good;
import com.xmj.mapper.GoodMapper;



public class GoodService {
	private GoodMapper goodMapper = new GoodMapper();
		//分頁查詢
		public DataVO<Good> queryByPage(int currentPage,int pageSize){
			DataVO<Good> dataVO = new DataVO<Good>();
			List<Good> goods = goodMapper.queryByPage(currentPage,pageSize);
			dataVO.setData(goods);
			dataVO.setCode(0);
		    dataVO.setMsg("");
		    dataVO.setCount(goods.size());
			return dataVO;
		}
		
		//查詢當前頁的資料集合
		public int getTotalCount() {
			return goodMapper.getTotalCount();
		}
		
		
		//刪
		public int deleteGoodById(int id) {
			if(goodMapper.isExist(id)) {
				goodMapper.deleteById(id);
				System.out.println("洗掉商品成功!");
				return 200;
			}
			else 
				System.out.println("這個商品不存在!");
				return 100;
		}
		
		//查
		public Good queryGoodById(int id) {
			if(goodMapper.isExist(id)) {
				return goodMapper.queryById(id);
			}
			System.out.println("這個商品不存在!");
			return null;
		}
		
		//查詢所有
		public List<Good> queryAll(){
			return goodMapper.queryAll();
		}
		
		
		
		//改
		public int updateGoodById(int id,Good good) throws ClassNotFoundException {
			if(goodMapper.isExist(id)) {
				goodMapper.updateById(id, good);
				System.out.println("修改商品成功!");
				return 200;
			}
			System.out.println("這個商品不存在!");
			return 100;
		}
		
		//增
		public boolean addGood(Good good) {
			if(!goodMapper.isExist(good.getId())) {
				System.out.println("添加商品成功!");
				return goodMapper.add(good);
			}else {
			System.out.println("這個商品已存在!");
			return false;
		}
		}
	
}


UserService業務層

同樣可以搬前面已經寫好的方法,稍加修改就OK了

package com.xmj.service;

import java.util.List;

import com.xmj.entity.DataVO;
import com.xmj.entity.User;
import com.xmj.mapper.UserMapper;

public class UserService {
	private UserMapper userMapper = new UserMapper();
	//分頁查詢
	public DataVO<User> queryByPage(int currentPage,int pageSize){
		DataVO<User> dataVO = new DataVO<User>();
		List<User> goods = userMapper.queryByPage(currentPage,pageSize);
		dataVO.setData(goods);
		dataVO.setCode(0);
	    dataVO.setMsg("");
	    dataVO.setCount(goods.size());
		return dataVO;
	}
	
	//查詢當前頁的資料集合
	public int getTotalCount() {
		return userMapper.getTotalCount();
	}
	
	
	//刪
	public int deleteUserById(int id) {
		if(userMapper.isExist(id)) {
			userMapper.deleteById(id);
			System.out.println("洗掉用戶成功!");
			return 200;
		}
		else 
			System.out.println("這個用戶不存在!");
			return 100;
	}
	
	//查
	public User queryUserById(int id) {
		if(userMapper.isExist(id)) {
			return userMapper.queryById(id);
		}
		System.out.println("這個用戶不存在!");
		return null;
	}
	
	//查詢所有
	public List<User> queryAll(){
		return userMapper.queryAll();
	}
	
	
	
	//改
	public int updateUserById(int id,User good) throws ClassNotFoundException {
		if(userMapper.isExist(id)) {
			userMapper.updateById(id, good);
			System.out.println("修改用戶成功!");
			return 200;
		}
		System.out.println("這個用戶不存在!");
		return 100;
	}
	
	//增
	public boolean addUser(User good) {
		if(!userMapper.isExist(good.getId())) {
			System.out.println("添加用戶成功!");
			return userMapper.add(good);
		}else {
		System.out.println("這個用戶已存在!");
		return false;
	}
	}

}

這是當前資料庫User表的內容

在這里插入圖片描述
這是當前資料庫Good表的內容
在這里插入圖片描述

我們建個Test測驗類來看看吧

Test.java測驗類


package com.xmj.test;

import java.util.Date;
import java.util.List;

import com.xmj.entity.Good;
import com.xmj.entity.User;
import com.xmj.service.GoodService;
import com.xmj.service.UserService;


public class Test {
	public static void main(String[] args) throws Exception{
		GoodService goodService = new GoodService();
		UserService userService = new UserService();
		Date time = new Date();
		//通過id來查找
		System.out.println(goodService.queryGoodById(111113));
		System.out.println(userService.queryUserById(11112));
		
		//添加
		System.out.println(goodService.addGood(new Good("新商品",(float)2.5,43,43,"測驗","測驗")));
		System.out.println(userService.addUser(new User("新用戶","dsa",432,"333333",34,"dsasa",time,2323,"343333")));
		
		//查詢全部
		List<Good> goods = goodService.queryAll();
		for(Good good : goods){
			System.out.println(good.getName());
		}
		
		List<User> users = userService.queryAll();
		for(User user : users){
			System.out.println(user.getName());
		}
		
		//通過id來修改		
//		System.out.println(userService.updateUserById(11112, new User("222222","dsa",432,"333333",34,"dsasa",time,2323,"343333")));
//		System.out.println(goodService.updateGoodById(11112, new Good("測驗",(float)222,43,43,"測驗","測驗")));
			

		//通過id來洗掉
//		System.out.println(goodService.deleteGoodById(111113));
//		System.out.println(userService.deleteUserById(1111));
	}
}

在這里插入圖片描述

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/387886.html

標籤:java

上一篇:C語言面向物件(上):面向物件三大特性的實作

下一篇:OnTriggerEnter2D內部的UnityFor回圈有時會導致多種結果

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • Rust中的智能指標:Box<T> Rc<T> Arc<T> Cell<T> RefCell<T> Weak

    Rust中的智能指標是什么 智能指標(smart pointers)是一類資料結構,是擁有資料所有權和額外功能的指標。是指標的進一步發展 指標(pointer)是一個包含記憶體地址的變數的通用概念。這個地址參考,或 ” 指向”(points at)一些其 他資料 。參考以 & 符號為標志并借用了他們所 ......

    uj5u.com 2023-04-20 07:24:10 more
  • Java的值傳遞和參考傳遞

    值傳遞不會改變本身,參考傳遞(如果傳遞的值需要實體化到堆里)如果發生修改了會改變本身。 1.基本資料型別都是值傳遞 package com.example.basic; public class Test { public static void main(String[] args) { int ......

    uj5u.com 2023-04-20 07:24:04 more
  • [2]SpinalHDL教程——Scala簡單入門

    第一個 Scala 程式 shell里面輸入 $ scala scala> 1 + 1 res0: Int = 2 scala> println("Hello World!") Hello World! 檔案形式 object HelloWorld { /* 這是我的第一個 Scala 程式 * 以 ......

    uj5u.com 2023-04-20 07:23:58 more
  • 理解函式指標和回呼函式

    理解 函式指標 指向函式的指標。比如: 理解函式指標的偽代碼 void (*p)(int type, char *data); // 定義一個函式指標p void func(int type, char *data); // 宣告一個函式func p = func; // 將指標p指向函式func ......

    uj5u.com 2023-04-20 07:23:52 more
  • Django筆記二十五之資料庫函式之日期函式

    本文首發于公眾號:Hunter后端 原文鏈接:Django筆記二十五之資料庫函式之日期函式 日期函式主要介紹兩個大類,Extract() 和 Trunc() Extract() 函式作用是提取日期,比如我們可以提取一個日期欄位的年份,月份,日等資料 Trunc() 的作用則是截取,比如 2022-0 ......

    uj5u.com 2023-04-20 07:23:45 more
  • 一天吃透JVM面試八股文

    什么是JVM? JVM,全稱Java Virtual Machine(Java虛擬機),是通過在實際的計算機上仿真模擬各種計算機功能來實作的。由一套位元組碼指令集、一組暫存器、一個堆疊、一個垃圾回收堆和一個存盤方法域等組成。JVM屏蔽了與作業系統平臺相關的資訊,使得Java程式只需要生成在Java虛擬機 ......

    uj5u.com 2023-04-20 07:23:31 more
  • 使用Java接入小程式訂閱訊息!

    更新完微信服務號的模板訊息之后,我又趕緊把微信小程式的訂閱訊息給實作了!之前我一直以為微信小程式也是要企業才能申請,沒想到小程式個人就能申請。 訊息推送平臺🔥推送下發【郵件】【短信】【微信服務號】【微信小程式】【企業微信】【釘釘】等訊息型別。 https://gitee.com/zhongfuch ......

    uj5u.com 2023-04-20 07:22:59 more
  • java -- 緩沖流、轉換流、序列化流

    緩沖流 緩沖流, 也叫高效流, 按照資料型別分類: 位元組緩沖流:BufferedInputStream,BufferedOutputStream 字符緩沖流:BufferedReader,BufferedWriter 緩沖流的基本原理,是在創建流物件時,會創建一個內置的默認大小的緩沖區陣列,通過緩沖 ......

    uj5u.com 2023-04-20 07:22:49 more
  • Java-SpringBoot-Range請求頭設定實作視頻分段傳輸

    老實說,人太懶了,現在基本都不喜歡寫筆記了,但是網上有關Range請求頭的文章都太水了 下面是抄的一段StackOverflow的代碼...自己大修改過的,寫的注釋挺全的,應該直接看得懂,就不解釋了 寫的不好...只是希望能給視頻網站開發的新手一點點幫助吧. 業務場景:視頻分段傳輸、視頻多段傳輸(理 ......

    uj5u.com 2023-04-20 07:22:42 more
  • Windows 10開發教程_編程入門自學教程_菜鳥教程-免費教程分享

    教程簡介 Windows 10開發入門教程 - 從簡單的步驟了解Windows 10開發,從基本到高級概念,包括簡介,UWP,第一個應用程式,商店,XAML控制元件,資料系結,XAML性能,自適應設計,自適應UI,自適應代碼,檔案管理,SQLite資料庫,應用程式到應用程式通信,應用程式本地化,應用程式 ......

    uj5u.com 2023-04-20 07:22:35 more