使用MongoDB驱动程序在Java中操作POJO对象

huangapple go评论80阅读模式
英文:

Using MongoDB driver POJO's with Java

问题

EDIT: 我可以使用建议的此处链接中的POJO示例,在控制台中输出用户列表,但没有像下面显示的 Object id。这是否是导致输出未显示在 JSP 页面上的问题?

用户 [邮箱=didi@abc.com, 全名=Didi Dee, 密码=asdfwle]
用户 [邮箱=lucy@abc.com, 全名=Lucy Liu, 密码=lalla]

我期望的结果如下所示,在浏览器中在每个标题下显示用户详细信息:

使用MongoDB驱动程序在Java中操作POJO对象

这是在 DAO 类中列出用户的新方法:

@Override
public List<User> listAll() {
    List<User> userList = new ArrayList<User>();    
    database.getCollection("User", User.class).find().into(userList);
    for (User u : userList) {
        System.out.println(u.toString());
    }
    return userList;
}

我的 服务类

public List<User> listUser() {
    List<User> userList = userDAO.listAll();			
    return userList;
}

控制器

UserService userService = new UserService(request, response);
List<User> userList = userService.listUser();
request.setAttribute("userList", userList); // 供 jsp 获取属性
String list_user_page = "user_list.jsp";
RequestDispatcher rd = request.getRequestDispatcher(list_user_page);
rd.forward(request, response);

JSP 页面来显示输出:

<c:forEach items="${userList}" var="user" begin="1">
    <tr>    		
        <td>${user.userId}</td>
        <td>${user.email}</td>
        <td>${user.fullName}</td>

        <td><a href="edit_user?id=${user.userId}">编辑</a>&nbsp;<a
            href="javascript:void(0);" class="deleteLink" id="${user.userId}">删除</a>
        </td>
    </tr>
</c:forEach>
英文:

EDIT: I can use the POJO example with the suggested post to output a list of users in the console, but no Object id as shown below. Is that the problem causing output not showing to the JSP page?

User [email=didi@abc.com, fullName=Didi Dee, password=asdfwle]
User [email=lucy@abc.com, fullName=Lucy Liu, password=lalla]

What I expect the result like below, that show user details under each heading on the browser,

使用MongoDB驱动程序在Java中操作POJO对象

Here is the new method to list user in DAO class

@Override
public List&lt;User&gt; listAll() {
	List&lt;User&gt; userList = new ArrayList&lt;User&gt;();    
	database.getCollection(&quot;User&quot;, User.class).find().into(userList);
    	for (User u : userList) {
		System.out.println(u.toString());
	}

	return userList;
}

My service class

public List&lt;User&gt; listUser() {
	List&lt;User&gt; userList = userDAO.listAll();			
	return userList;
}

The Controller

UserService userService = new UserService(request, response);

List&lt;User&gt; userList = userService.listUser();

request.setAttribute(&quot;userList&quot;, userList); // for jsp to get Attribute

String list_user_page = &quot;user_list.jsp&quot;;
RequestDispatcher rd = request.getRequestDispatcher(list_user_page);
rd.forward(request, response);

The JSP to show the output.

&lt;c:forEach items=&quot;${userList}&quot; var=&quot;user&quot; begin=&quot;1&quot;&gt;
	&lt;tr&gt;    		
		&lt;td&gt;${user.userId}&lt;/td&gt;
		&lt;td&gt;${user.email}&lt;/td&gt;
		&lt;td&gt;${user.fullName}&lt;/td&gt;


		&lt;td&gt;&lt;a href=&quot;edit_user?id=${user.userId}&quot;&gt;Edit&lt;/a&gt; &amp;nbsp; &lt;a
			href=&quot;javascript:void(0);&quot; class=&quot;deleteLink&quot; id=&quot;${user.userId}&quot;&gt;Delete&lt;/a&gt;
		&lt;/td&gt;
	&lt;/tr&gt;
&lt;/c:forEach&gt;

答案1

得分: 2

假设如下:

您已经包含了以下代码:

CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
                                  fromProviders(PojoCodecProvider.builder().automatic(true).build()));

您的数据库包含以下格式的记录:

> db.User.find().pretty()
{
	"_id" : ObjectId("5f7f92c4d91d2c38583dbfba"),
	"fullname" : "Stu Dent",
	"email" : "student@uni.versity",
	"password" : "passWord"
}
{
	"_id" : ObjectId("5f7f9497d91d2c38583dbfbb"),
	"fullname" : "A. N. Other",
	"email" : "another@uni.versity",
	"password" : "strongerPassWord_1"
}

User 被定义为如下的 bean:

public class User
{
    private String fullname;
    private String email;
    private String password;
    
    public User()
    {
        // 默认的 bean 构造函数
    }

    // 省略了其他 getter 和 setter 方法

    @Override
    public String toString()
    {
        return "User [fullname=" + fullname + ", email=" + email + ", password=" + password + "]";
    }
}

以下代码将把数据库的内容读入 userList 列表中:

List<User> userList = new ArrayList<User>();
db.getCollection("User", User.class).find().into(userList);

要输出列表:

for (User u : userList)
{
    System.out.println(u.toString());
}

结果:

User [fullname=Stu Dent, email=student@uni.versity, password=passWord]
User [fullname=A. N. Other, email=another@uni.versity, password=strongerPassWord_1]

如果您坚持逐个记录循环,我建议使用以下代码:

FindIterable<Document> userTbl = db.getCollection("User").find();

for (Document doc: userTbl)
{
    User user = new User();
    user.setFullname(doc.getString("fullname"));
    user.setEmail(doc.getString("email"));
    user.setPassword(doc.getString("password"));
    
    System.out.println("User = " + user.toString());
}

会产生以下结果:

User = User [fullname=Stu Dent, email=student@uni.versity, password=passWord]
User = User [fullname=A. N. Other, email=another@uni.versity, password=strongerPassWord_1]
英文:

Assuming the following:

You've included

CodecRegistry pojoCodecRegistry = fromRegistries(MongoClientSettings.getDefaultCodecRegistry(),
                                  fromProviders(PojoCodecProvider.builder().automatic(true).build()));

Your database contains records in the following format:

&gt; db.User.find().pretty()
{
	&quot;_id&quot; : ObjectId(&quot;5f7f92c4d91d2c38583dbfba&quot;),
	&quot;fullname&quot; : &quot;Stu Dent&quot;,
	&quot;email&quot; : &quot;student@uni.versity&quot;,
	&quot;password&quot; : &quot;passWord&quot;
}
{
	&quot;_id&quot; : ObjectId(&quot;5f7f9497d91d2c38583dbfbb&quot;),
	&quot;fullname&quot; : &quot;A. N. Other&quot;,
	&quot;email&quot; : &quot;another@uni.versity&quot;,
	&quot;password&quot; : &quot;strongerPassWord_1&quot;
}

User is defined as a bean like this:

public class User
{
    private String fullname;
    private String email;
    private String password;
    
    public User()
    {
        // Default bean constructor
    }

    public String getFullname()
    {
        return fullname;
    }

    public void setFullname(String fullname)
    {
        this.fullname = fullname;
    }

    public String getEmail()
    {
        return email;
    }

    public void setEmail(String email)
    {
        this.email = email;
    }

    public String getPassword()
    {
        return password;
    }

    public void setPassword(String password)
    {
        this.password = password;
    }

    @Override
    public String toString()
    {
        return &quot;User [fullname=&quot; + fullname + &quot;, email=&quot; + email + &quot;, password=&quot; + password + &quot;]&quot;;
    }
}

The following code will read the contents of the database into the userList List:

List&lt;User&gt; userList = new ArrayList&lt;User&gt;();
db.getCollection(&quot;User&quot;, User.class).find().into(userList);

To output the list:

for (User u : userList)
{
    System.out.println(u.toString());
}

Result:

User [fullname=Stu Dent, email=student@uni.versity, password=passWord]
User [fullname=A. N. Other, email=another@uni.versity, password=strongerPassWord_1]

If you insist on looping through the individual records, then I would suggest:

FindIterable&lt;Document&gt; userTbl = db.getCollection(&quot;User&quot;).find();

for (Document doc: userTbl)
{
    User user = new User();
    user.setFullname(doc.getString(&quot;fullname&quot;));
    user.setEmail(doc.getString(&quot;email&quot;));
    user.setPassword(doc.getString(&quot;password&quot;));
    
    System.out.println(&quot;User = &quot; + user.toString());
}

Which produces:

User = User [fullname=Stu Dent, email=student@uni.versity, password=passWord]
User = User [fullname=A. N. Other, email=another@uni.versity, password=strongerPassWord_1]

答案2

得分: 1

以下是您要翻译的内容:

无法显示用户列表的原因是我忘记将数据库连接放到我的控制器中,这与人们通常在JPA注解中使用的方式不同,在其中添加了一个JPA层。

response.setContentType("text/html");
MongoDB.getMongoDB();

在调试困难时,特别感谢Spuggiehawk提供的建议答案,以便在编写较少的代码时进行调试。

英文:

The reason I can't show the user list because I forgot put the database connection to my controller that different from people used to do with JPA annotation and add a JPA layer on it.

response.setContentType(&quot;text/html&quot;);
MongoDB.getMongoDB();

使用MongoDB驱动程序在Java中操作POJO对象

Especially thanks Spuggiehawk for the suggested answer to write less code during a hard time debuggin.

huangapple
  • 本文由 发表于 2020年10月8日 19:23:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/64261496.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定