首页 > 编程语言 >35、Java——一个案例学会Dao+service层对数据表的增删改查

35、Java——一个案例学会Dao+service层对数据表的增删改查

时间:2022-11-05 23:05:43浏览次数:46  
标签:return Animal service 数据表 connection animal aid Java public


✅作者简介:热爱国学的Java后端开发者,修心和技术同步精进。

文章目录

  • ​​案例​​
  • ​​建表​​
  • ​​配置​​
  • ​​Animal类​​
  • ​​DBUtils数据库工具类​​
  • ​​DateUtils日期类​​
  • ​​AnimalDaoImpl类​​
  • ​​AnimalServiceImpl类​​
  • ​​AnimalTest测试类​​

案例

  使用读取配置文件的形式连接数据库,(Dao层+service层)对animal表进行增删改查操作。

animal表字段如下
  aid int 主键 自增长 -->宠物编号
  name varchar(10) 非空 -->宠物名称
  age int 非空 -->宠物年龄
  birthday Date 非空

建表

CREATE TABLE IF NOT EXISTS `animal`(
`aid` INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(10) NOT NULL,
`age` INT NOT NULL,
`birthday` DATE
);

配置

  添加mysql-connector-java-5.1.0-bin.jar文件并使用。

  添加db.properties文件

35、Java——一个案例学会Dao+service层对数据表的增删改查_开发语言

Animal类

  定义一个Animal类,添加和animal表字段相同的私有变量

// 定义属性
private int aid;
private String name;
private int age;
private Date birthday;

  添加一个无参构造

public Animal() {
super();
}

  添加一个全部字段的有参构造

public Animal(int aid, String name, int age, Date birthday) {
super();
this.aid = aid;
this.name = name;
this.age = age;
this.birthday = birthday;
}

  添加一个不带aid字段的有参构造

public Animal(String name, int age, String gender, Date birthday,
String identityCard, String phone, String address, double salary) {
super();
this.name = name;
this.age = age;
this.birthday = birthday;
}

  给私有变量添加get/set方法

public int getAid() {
return aid;
}

public void setAid(int aid) {
this.aid = aid;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public Date getBirthday() {
return birthday;
}

public void setBirthday(Date birthday) {
this.birthday = birthday;
}

  重写ToString方法

@Override
public String toString() {
return "Animal [aid=" + aid + ", name=" + name + ", age=" + age
+ ", birthday=" + birthday + "]";
}

DBUtils数据库工具类

  声明一个ThreadLocal对象,用来存储Connection连接对象;注册驱动、获取连接、然后释放资源方法。

private static final Properties PROPERTIES = new Properties();
// 声明一个ThreadLocal<Connection>对象,用来存储Connection连接对象
private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

static {
InputStream is = DBUtils.class.getResourceAsStream("/db.properties");
try {
PROPERTIES.load(is);
// 1、注册驱动
Class.forName(PROPERTIES.getProperty("driver"));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 2、获取连接方法
public static Connection getConnection() {
Connection connection = threadLocal.get();
// 2、获取连接对象
try {
// 如果连接对象为null,创建一个连接对象
if (connection == null) {
connection = DriverManager.getConnection(
PROPERTIES.getProperty("url"),
PROPERTIES.getProperty("username"),
PROPERTIES.getProperty("password"));
threadLocal.set(connection);
}
} catch (SQLException e) {
e.printStackTrace();
}
return connection;

}

// 3、释放资源方法
public static void closeAll(ResultSet resultSet, Statement statement,
Connection connection) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
// 移除 ThreadLocal<Connection> 对象
threadLocal.remove();
}
} catch (SQLException e) {
e.printStackTrace();
}
}

  开启事务

public static void startTransaction() {
Connection connection = getConnection();
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}

  提交事务

public static void commitTransaction() {
Connection connection = getConnection();
try {
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(null, null, connection);
}
}

  回滚事务

public static void rollbackTransaction() {
Connection connection = getConnection();
try {
connection.rollback();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(null, null, connection);
}
}

DateUtils日期类

public class DateUtils {
// 声明一个SimpleDateFormat类型的静态常量
public static final SimpleDateFormat SIMPLEDATEFORMAT=new SimpleDateFormat("yyyy-MM-dd");

// 定义方法实现将字符串类型的数据转换成java.util.Date类型
public static java.util.Date strToUtilDate(String strDate){
try {
return SIMPLEDATEFORMAT.parse(strDate);
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}

// 定义方法实现将java.util.Date类型转换为字符串
public static String utilDateToString(java.util.Date utilDate){
return SIMPLEDATEFORMAT.format(utilDate);
}

// 定义方法实现架构java.util.Date类型转换为java.sql.Date类型
public static java.sql.Date utilDateToSqlDate(java.util.Date utilDate){
return new java.sql.Date(utilDate.getTime());
}
}

AnimalDaoImpl类

  DAO层叫数据访问层,全称为data access object,属于一种比较底层,比较基础的操作,具体到对于某个表的增删改查,也就是说某个DAO一定是和数据库的某一张表一一对应的,其中封装了增删改查基本操作,建议DAO只做原子操作,增删改查。

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

public class AnimalDaoImpl {

//全局变量
PreparedStatement preS=null;
Connection connection;

//增
public int insert(Animal animal){

//获取链接
connection=DBUtils.getConnection();
String sql="insert into animal values(?,?,?,?);";

try {
preS=connection.prepareStatement(sql);
// 绑定参数
preS.setInt(1, animal.getAid());
preS.setString(2, animal.getName());
preS.setInt(3, animal.getAge());
preS.setDate(4, DateUtils.utilDateToSqlDate(animal.getBirthday()));

return preS.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBUtils.closeAll(null, preS, null);
}
return 0;
}

//删
public int delete(int aid) {

//获取链接
connection = DBUtils.getConnection();
String sql = "delete from animal where aid = ?;";

try {
preS = connection.prepareStatement(sql);
// 绑定参数
preS.setInt(1, aid);

return preS.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(null, preS, null);
}
return 0;
}

//改
public int update(Animal animal) {

//获取链接
connection = DBUtils.getConnection();
String sql = "update animal set name = ?,age = ?,birthday= ? where aid=?;";

try {
preS = connection.prepareStatement(sql);
// 绑定参数
preS.setString(1, animal.getName());
preS.setInt(2, animal.getAge());
preS.setDate(3, DateUtils.utilDateToSqlDate(animal.getBirthday()));
preS.setInt(4, animal.getAid());

return preS.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(null, preS, null);
}
return 0;
}

//查(单个)
public Animal select(int aid) {
ResultSet resultSet = null;
Animal animal = null;

//获取连接
connection = DBUtils.getConnection();
String sql = "select * from animal where aid = ?";

try {
preS = connection.prepareStatement(sql);

// 绑定参数
preS.setInt(1, aid);
resultSet = preS.executeQuery();

if (resultSet.next()) {
animal=new Animal(aid, resultSet.getString(2), resultSet.getInt(3), resultSet.getDate(4));
}

return animal;
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(resultSet, preS, null);
}
return null;
}

//查(全部)
public List<Animal> selectAll() {
ResultSet resultSet = null;
Animal animal = null;
List<Animal> animalList = new ArrayList<Animal>();

//获取连接
connection = DBUtils.getConnection();
String sql = "select * from animal";

try {
preS = connection.prepareStatement(sql);
resultSet = preS.executeQuery();

while (resultSet.next()) {
animal=new Animal(resultSet.getInt(1), resultSet.getString(2), resultSet.getInt(3), resultSet.getDate(4));
animalList.add(animal);
}

return animalList;
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.closeAll(resultSet, preS, null);
}
return null;
}
}

AnimalServiceImpl类

  Service层叫服务层,被称为服务,粗略的理解就是对一个或多个DAO进行的再次封装,封装成一个服务,所以这里也就不会是一个原子操作了,需要事物控制。

public class AnimalServiceImpl {

//定义AnimalDaoImpl对象
AnimalDaoImpl animalDao=new AnimalDaoImpl();

//新增信息
public boolean addNewData(Animal animal) {
int num=animalDao.insert(animal);
if(num!=0){
return true;
}else{
return false;
}
}

//删除信息
public boolean delDate(int aid){
int num=animalDao.delete(aid);
if(num!=0){
return true;
}else{
return false;
}
}

//修改信息
public boolean updateDate(Animal animal){
int num=animalDao.update(animal);
if(num!=0){
return true;
}else{
return false;
}
}

//查询信息
public boolean selectDate(int aid){
Animal animal=animalDao.select(aid);
if(animal!=null){
return true;
}else{
return false;
}
}

//查询所有信息
public void selectAllDates(){
List<Animal> animalList=animalDao.selectAll();
if(animalList.size()>0){
System.out.println("****所有动物信息****");
for (Animal animal : animalList) {
System.out.println(animal);
}
}
}
}

AnimalTest测试类

package cn.bdqn.demo02;
public class AnimalTest {

public static void main(String[] args) {

//创建AnimalServiceImpl对象
AnimalServiceImpl animalServiceImpl = new AnimalServiceImpl();

//增加三条数据
Animal animal1 = new Animal(1, "旺财", 3,DateUtils.strToUtilDate("2019-08-18"));
Animal animal2 = new Animal(2, "tom", 4,DateUtils.strToUtilDate("2018-06-25"));
Animal animal3 = new Animal(3, "佩奇", 5,DateUtils.strToUtilDate("2017-07-02"));
animalServiceImpl.addNewData(animal1);
animalServiceImpl.addNewData(animal2);
animalServiceImpl.addNewData(animal3);

//删(aid=3)的数据
animalServiceImpl.delDate(3);

//改
Animal animal4 = new Animal(1, "旺财", 4,DateUtils.strToUtilDate("2018-12-18"));
animalServiceImpl.updateDate(animal4);

//查一条(aid=2)的数据
animalServiceImpl.selectDate(2);

//查全部
animalServiceImpl.selectAllDates();
}
}

35、Java——一个案例学会Dao+service层对数据表的增删改查_sql_02


标签:return,Animal,service,数据表,connection,animal,aid,Java,public
From: https://blog.51cto.com/u_15740516/5826333

相关文章

  • 34、Java——一个案例学会Dom4j解析技术对XML文件的增删改查
    ✅作者简介:热爱国学的Java后端开发者,修心和技术同步精进。案例使用Dom4j解析技术实现对animal.xml文件进行增删改查操作。链接:​​dom4j包下载​​​将dom4j的jar包导入......
  • 【JAVA高级】——初识JDBC中Service业务逻辑层
    ✅作者简介:热爱国学的Java后端开发者,修心和技术同步精进。本文目录​​......
  • 【JAVA高级】——初识JDBC中DAO数据访问对象
    ✅作者简介:热爱国学的Java后端开发者,修心和技术同步精进。本文目录​​......
  • 33、Java——汽车租赁系统(对象+JDBC)
    ✅作者简介:热爱国学的Java后端开发者,修心和技术同步精进。本文目录​​覆盖知识​​​​项目需求​​​​设计步骤 ​​​​开发思路 ​​​​类的属性和方法​​​​代码......
  • 大厂面试,欢聚时代四年多经验的Java面经
    欢聚时代一面(1h)先做下自我介绍,固定环节面试官:既然你用Java语言,那我们先讲点Java基础的东西吧,你说下Java有哪些锁?按照机制区分的话,Java中包含的锁可以分为公平锁和非公平锁......
  • 使用 Java 类生成 MD5 加密字符
    MD5常用于密码加密,例如,在注册时可以将密码转为MD5再放入数据库,在登录时校验登录密码和数据库存放的加密密码是否一致,来保证密码在数据库中存储的安全性。下面介绍使用......
  • SAP Java Connector 的配置指南
    SAPJava连接器(JCo)3.1需要Java运行时环境(JRE)版本8或11。有关受支持平台和Java运行时环境的最新详细列表,请参阅SAP说明2786882。最新版本的SAPJava......
  • SAP Java Connector 组件介绍
    SAPJavaConnector3.1运行时环境由两部分组成:sapjco3.jar-包含JCo的Java运行时类的存档{libraryprefix}sapjco3{sharedlibraryextension}-包含JCo原生......
  • java 文件类
    java常用的文件操作1~文件的创建(三种不同方法):(1)根据路径构建一个File对象:newFile(Stringpathname)(2)根据父目录文件+子路径构建:newFile(Fileparent,Stringchild)(3)......
  • JavaScript修改修改图片dpi
    欢迎关注前端早茶,与广东靓仔携手共同进阶​​​​前端早茶专注前端,一起结伴同行,紧跟业界发展步伐~ 一、原理changeDPI提供了2个实用函数,可以更改画布生成的图像的dpi,无......