【发布时间】:2012-06-18 21:05:42
【问题描述】:
我正在为网站编写功能区/成就系统,我必须为系统中的每个功能区编写一些逻辑。例如,如果您是注册网站的前 2,000 人中或在论坛中发帖 1,000 条之后,您就可以获得勋带。这个想法非常类似于 stackoverflow 的徽章,真的。
因此,显然每个功能区都在数据库中,但它们还需要一些逻辑来确定用户何时获得功能区。
按照我的编码方式,Ribbon 是一个简单的抽象类:
@Entity
@Table(name = "ribbon")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "ribbon_type")
public abstract class Ribbon
{
@Id
@Column(name = "id", nullable = false, length = 8)
private int id;
@Column(name = "title", nullable = false, length = 64)
private String title;
public Ribbon()
{
}
public abstract boolean isEarned(User user);
// ... getters/setters...
}
您可以看到我将继承策略定义为SINGLE_TABLE(因为我必须编写 50 个功能区,并且我不需要为其中任何一个添加额外的列)。
现在,一个特定的功能区将像这样实现,例如:
@Entity
public class First2000UsersRibbon extends Ribbon
{
@Autowired
@Transient
private UserHasRibbonDao userHasRibbonDao;
public First2000UsersRibbon()
{
super.setId(1);
super.setTitle("Between the first 2,000 users who registered to the website");
}
@Override
public boolean isEarned(User user)
{
if(!userHasRibbonDao.userHasRibbon(user, this))
{
// TODO
// All the logic to determine whether the user earned the ribbon
// i.e. check whether the user is between the first 2000 users who registered to the website
// Other autowired DAOs are needed
}
else
{
return true;
}
return false;
}
}
问题是userHasRibbonDao 在isEarned() 方法中为空,所以会抛出NullPointerException。
我认为将 DAO 自动装配到域对象中是错误的,但在 this topic 他们告诉我这是正确的方法(域驱动设计)。
我在 GitHub 上分享了一个无效的非常简单的示例:https://github.com/MintTwist/TestApp(记得更改 /WEB-INF/properties/jdbc.properties 中的连接详细信息并导入 test_app.sql 脚本)
非常感谢任何帮助。
谢谢!
更新 - 阅读第一个答案,我的方法似乎完全错误。考虑到可能有 50-70 种不同的功能区,您将如何理想地构建代码?谢谢
【问题讨论】:
-
>_
-
这里应该有一些github URL吗?
-
谢谢@NathanHughes,我刚刚发布了他们在另一个问题上告诉我的内容。
-
抱歉@madth3,我忘记添加了。它现在在那里:)
标签: java spring spring-mvc dao autowired