gpt4 book ai didi

java - 使用 dao 时初始化对象的最佳方法

转载 作者:行者123 更新时间:2023-11-30 00:45:06 28 4
gpt4 key购买 nike

我正在使用 MySQL 构建 Tomcat 应用程序。我正在使用 DAO 模式与数据库对话。我无法确定在何处初始化对象中的字段。

主要是为了节省打字...我正在使用 EclipseLink JPA 从表生成模型实体。我正在手工编写 DAO 代码。我正在手工编写模型,但这似乎更容易。

我遇到的问题是将对象写回数据库时所有默认的空值。例如,该表包含一堆 id 列。并非所有这些都具有对象的每个实例的上下文。创建对象似乎效率低下,并且必须将所有字段设置为零才能将它们保存到数据库中。如果他们没有上下文,我想就别管他们了。即我只想设置与我当时正在做的事情相关的字段。

似乎最好使用模型类中的构造函数来初始化它们。但如果我这样做,EclipseLink 将在我下次生成模型时覆盖它们。

让 DAO 更新方法检查空值并将其设置为零似乎是一个拼凑。我想我还可以使用工厂来创建和初始化模型类。

但我想知道我是否想得太多了......这些解决方案中的任何一个都可以。但必须有一个公认的模式。

我应该如何处理它?<​​/p>

谢谢

模型只是 getter 和 setter。构造函数为空。

代码摘录如下...

Notice notice = new Notice();
notice.setEvent("Welcome");
notice.setUserid(user.getId());
noticeDao.updateNotice(notice);

DAO:

//this seems inefficient
if(notice.getTravid() == null) notice.setTravid(0L);
if(notice.getBusid() == null) notice.setBusid(0L);
if(notice.getSaveid() == null) notice.setSaveid(0L);
if(notice.getTargid() == null) notice.setTargid(0L);
if(notice.getTestmode() == null) notice.setTestmode(false);

String SQLupdate = "UPDATE notices SET "
+ "userid = ?, "
+ "travid = ?, "
+ "busid = ?, "
+ "saveid = ?, "
+ "targid = ?, "
+ "testmode = ?, "
+ "event = ?, "
+ "status = ?, "
+ "error = ?, "
+ "created = ?, "
+ "modified = ?, "
+ "log = ? "
+ "WHERE id = ?";
ps = conn.prepareStatement(SQLupdate);
ps.setLong(1, notice.getUserid());
ps.setLong(2, notice.getTravid());
ps.setLong(3, notice.getBusid());
ps.setLong(4, notice.getSaveid());
ps.setLong(5, notice.getTargid());
ps.setBoolean(6, notice.getTestmode());
ps.setString( 7, notice.getEvent());
ps.setString( 8, notice.getStatus());
ps.setString( 9, notice.getError());
ps.setObject(10, notice.getCreated());
ps.setObject(11, notice.getModified());
ps.setString(12, notice.getLog());
ps.setLong( 13, notice.getId());
ps.executeUpdate();

数据库:

CREATE TABLE `notices` (
`id` int(20) unsigned NOT NULL AUTO_INCREMENT,
`userid` int(20) unsigned NOT NULL DEFAULT '0',
`travid` int(20) unsigned NOT NULL DEFAULT '0',
`busid` int(20) unsigned NOT NULL DEFAULT '0',
`saveid` int(20) unsigned NOT NULL DEFAULT '0',
`targid` int(20) unsigned NOT NULL DEFAULT '0',
`testmode` tinyint(1) DEFAULT '0',
`event` varchar(40) DEFAULT NULL,
`status` varchar(20) DEFAULT 'Pending',
`error` varchar(255) DEFAULT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
`log` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=49 DEFAULT CHARSET=utf8

数据库表是这样的:

ID

一般来说,代码如下所示:

最佳答案

为了解决您的具体问题,是否有办法告诉 eclipselink 设置字段的默认值?

但是您的数据库设计可能存在更深层次的问题。 *id 字段不是外键吗?他们应该是。如果它们外键,那么对于特定字段没有上下文的行,它们在数据库中的值应该为null,而不是0L

在更深层次上,如果它们中的大多数在大多数行中都没有上下文——也就是说,没有上下文是一种异常(exception)而不是常态——那么也许你的数据库设计本身就不好。您可能正在设计一个通用表,并且将从将单个表分解为多个表中受益。

关于java - 使用 dao 时初始化对象的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21446269/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com