【问题标题】:I need to cast an object to string then retrieve it by casting it back to my object我需要将一个对象转换为字符串,然后通过将其转换回我的对象​​来检索它
【发布时间】:2019-07-23 11:46:06
【问题描述】:

我需要学习如何创建我的自定义 .tostring 和 .fromstring

我已尝试将其投射回对象,但它似乎不起作用 我也尝试检索对象并将其转换为字符串,然后比较字符串,但它仍然不起作用

问题从这里开始,所以 .toString() 试图绕过问题

我只能保存元素 id,但是在同时处理三个不同的表时检索时会很忙

我想要一个持久化来保存我可以通过它实现的所有对象,但在检索期间必须创建三个查询,这与我目前对事件实体所做的不同

detached entity passed to persist: entities.Event

package entities;
// Generated Jul 23, 2019 11:11:55 AM by Hibernate Tools 4.3.1

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;




/**
 * Event generated by hbm2java
 */
public class Event  implements java.io.Serializable {


     private Integer id;
     private String image;
     private String location;
     private int upto100;
     private Integer upto300;
     private Integer upto500;
     private Integer upto1000;
     private int phoneno;
     private String scenario;
     private String name;
     private String mail;
     private Users owner;
     private String description;

    public Event() {
    }


    public Event(String image, String location, int upto100, int phoneno, String scenario, String name, String mail) {
        this.image = image;
        this.location = location;
        this.upto100 = upto100;
        this.phoneno = phoneno;
        this.scenario = scenario;
        this.name = name;
        this.mail = mail;
    }
    public Event(String image, String location, int upto100, Integer upto300, Integer upto500, Integer upto1000, int phoneno, String scenario, String name, String mail, Users owner, String description) {
       this.image = image;
       this.location = location;
       this.upto100 = upto100;
       this.upto300 = upto300;
       this.upto500 = upto500;
       this.upto1000 = upto1000;
       this.phoneno = phoneno;
       this.scenario = scenario;
       this.name = name;
       this.mail = mail;
       this.owner = owner;
       this.description = description;
    }

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
    public String getImage() {
        return this.image;
    }

    public void setImage(String image) {
        this.image = image;
    }
    public String getLocation() {
        return this.location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
    public int getUpto100() {
        return this.upto100;
    }

    public void setUpto100(int upto100) {
        this.upto100 = upto100;
    }
    public Integer getUpto300() {
        return this.upto300;
    }

    public void setUpto300(Integer upto300) {
        this.upto300 = upto300;
    }
    public Integer getUpto500() {
        return this.upto500;
    }

    public void setUpto500(Integer upto500) {
        this.upto500 = upto500;
    }
    public Integer getUpto1000() {
        return this.upto1000;
    }

    public void setUpto1000(Integer upto1000) {
        this.upto1000 = upto1000;
    }
    public int getPhoneno() {
        return this.phoneno;
    }

    public void setPhoneno(int phoneno) {
        this.phoneno = phoneno;
    }
    public String getScenario() {
        return this.scenario;
    }

    public void setScenario(String scenario) {
        this.scenario = scenario;
    }
    public String getName() {
        return this.name;
    }

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

    public void setMail(String mail) {
        this.mail = mail;
    }
    public Users getOwner() {
        return this.owner;
    }

    public void setOwner(Users owner) {
        this.owner = owner;
    }
    public String getDescription() {
        return this.description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    /*public String toStreng(Event event) throws JsonProcessingException {
        return new ObjectMapper().writeValueAsString(event);
    }

    public Event fromStreng(String string) throws IOException {
        return new ObjectMapper().readValue(string, Event.class);
    }*/


}



这是我需要覆盖 .tostring 和 .fromstring 的类 下面的页面是我必须将对象转换为字符串的地方

<%-- 
    Document   : Book
    Created on : Jul 21, 2019, 8:27:27 PM
    Author     : Tariana
--%>

<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="org.hibernate.service.ServiceRegistry"%>
<%@page import="org.hibernate.cfg.Configuration"%>
<%@page import="org.hibernate.service.ServiceRegistryBuilder"%>
<%@page import="org.hibernate.Session"%>
<%@page import="org.hibernate.Query"%>
<%@page import="org.hibernate.SessionFactory"%>
<%@page import="entities.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
    String eventid = (String) session.getAttribute("venueid");
    Users owner = new Users();
    int id = Integer.parseInt(eventid);

    SessionFactory sessionFactory;
    ServiceRegistry serviceRegistry;

    Configuration configuration = new Configuration();
    configuration.addAnnotatedClass(Users.class)
        .configure();

    serviceRegistry = new ServiceRegistryBuilder()
            .applySettings(configuration.getProperties())
            .configure("hibernate.cfg.xml")
            .build();        
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    Session sess = sessionFactory.openSession();
    String hql = "SELECT e FROM Event e WHERE e.id = :id";
    Query query = sess.createQuery(hql);
    query.setInteger("id", id);
    List<Event> products;
    List results = query.list();
    products = results;

    Users own = null;
    Event venues = null;
    String upto;

    Iterator<Event> itr = products.iterator();
    while(itr.hasNext()){
        Event g = itr.next();
        System.out.println(g.getUpto100());
        owner = g.getOwner();
        own = owner;
        venues = g;
    }
    System.out.println(own.getUsername());
    String owns = (String) own.getUsername();
    sess.close();
    if(venues.getUpto300() != null){
        upto = "upto300";
    }else if(venues.getUpto500() != null){
        upto = "upto500";
    }else if(venues.getUpto1000() != null){
        upto = "upto1000";
    }else{
        upto = "upto100";
    }
    session.setAttribute("owner", owner);
    session.setAttribute("venue", venues);
%>
<html>
    <head>
        <style>
            .navy{
                float: right;
            }
        </style>
        <%@include file = "BookHeader.jsp" %>
        <title>Book</title>
    </head>
    <body>
        <div id="lookbookHeader">
        <video autoplay poster="data:image/png;base64, <%=venues.getImage()%>" onerror="this.onerror=null;this.poster='event.png';" id="bgvid">

        </video>
        <div id="headerContentContainer">
            <h1 class="whitey"><%=venues.getName()%></h1>
            <div class="initial-arrow-small"></div>
        </div>
        </div>
        </div>
        <div id="introContent">
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
            <script src="https://cdn.jsdelivr.net/momentjs/2.14.1/moment.min.js"></script>
            <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
            <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css">
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
            <br>
            <h2>Book Venue</h2>
            <h5 class="lefty">Email:</h5> <h5 class="rightey"><%=venues.getMail()%></h5><br><br>
            <h5 class="lefty">Max Capacity:</h5> <h5 class="rightey"><%=upto%></h5><br><br>
            <h5 class="lefty">Price for up to 100 people:</h5> <h5 class="rightey"><%=venues.getUpto100()%></h5><br><br>
            <h5 class="lefty">Price for up to 300 people:</h5> <h5 class="rightey"><%=venues.getUpto300()%></h5><br><br>
            <h5 class="lefty">Price for up to 500 people:</h5> <h5 class="rightey"><%=venues.getUpto500() %></h5><br><br>
            <h5 class="lefty">Price for up to 1000 people:</h5> <h5 class="rightey"><%=venues.getUpto1000()%></h5><br><br>
            <h5 class="lefty">Phone no.:</h5> <h5 class="rightey"><%=venues.getPhoneno()%></h5><br><br>
            <h5 class="lefty">Location:</h5> <h5 class="rightey"><%=venues.getLocation()%></h5><br><br>
            <h5 class="lefty">Scenario:</h5> <h5 class="rightey"><%=venues.getScenario()%></h5><br><br>
            <h5 class="lefty">Posted By:</h5> <h5 class="rightey"><%=owns%></h5><br><br>
            <p class="lefty">Description:</p> <p class="rightey">
                <%=venues.getDescription()%>
            </p><br><br>
            <h4>Set Event Details</h4>
            <form action="/Eventer/Booking">
                <!--<script src="//code.jquery.com/jquery-1.10.2.js"></script>
                <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
                <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"/>
                <script>
                    $( "#from" ).datepicker().datepicker("setDate", "today");
                    $(function() {  
                        $( "#from" ).datepicker({   
                            defaultDate: "+0w",  
                            changeMonth: true,   
                            numberOfMonths: 1,
                            onClose: function( selectedDate ) {  
                              $( "#to" ).datepicker( "option", "minDate", "today" );
                              $( "#to" ).datepicker( "option", "minDate", selectedDate );
                              $( "#to" ).datepicker( "option", "maxDate", selectedDate);
                            }  
                        });  
                        $( "#to" ).datepicker({
                            defaultDate: "today",
                            changeMonth: true,
                            numberOfMonths: 1,
                            onClose: function( selectedDate ) {
                              $( "#from" ).datepicker( "option", "minDate", "today" );
                            }
                        });  
                    });  
                </script>
                <div class="form-group">
                    <label class="sr-only" for="eventedit">Start date:</label>
                    <input type="text" id="from" name="from" >
                </div>
                <div class="form-group">
                    <label class="sr-only" for="eventedit">End date:</label>
                    <input type="text" id="to" name = "to">
                </div>-->
                <div class="form-group">
                    <label for="Event Name">Event Name:</label>
                    <input type="text" class="form-control" name="eventname" id="" aria-describedby="helpId" placeholder="" required>
                    <small id="emailHelpId" class="form-text text-muted">Enter location of venue</small>
                </div>
                <div class='input-group date' id='datetimepicker1'>
                    <label for="Event Name">Set Event Date:</label>
                    <input name="date" type='text' class="form-control" id="" aria-describedby="helpId" required/><br>
                    <small id="helpId" class="form-text text-muted">Enter date of event</small>
                    <span class="input-group-addon">
                    <span class="glyphicon glyphicon-calendar"></span>
                    </span><br>
                </div>
                    <script>
                        $(function () {
                            $('#datetimepicker1').datetimepicker();
                            var minDate = $( "#datetimepicker1" ).datepicker( "option", "minDate" );
                            minDate.datepicker( "option", "minDate", "today" );
                        });
                      </script>
                      <h2>Choose Booking Capacity</h2>
                <div class="form-check">
                    <input type="radio" class="form-check-input" name="capacity" id="" checked value="upto100">
                    <label class="form-check-label">
                        <br>   
                        <i class="fa fa-1x" aria-hidden="true"><h3>Up to 100 people</h3></i>
                    </label>
                </div>
                <%
                    if(venues.getUpto300() != null){
                        %>
                        <div class="form-check">
                            <input type="radio" class="form-check-input" name="capacity" id="" value="upto300">
                            <label class="form-check-label">
                                <br>   
                                <i class="fa fa-1x" aria-hidden="true"><h3>Up to 300 people</h3></i>
                            </label>
                        </div>
                        <%
                    }
                    %>
                <%
                    if(venues.getUpto500() != null){
                        %>
                        <div class="form-check">
                            <input type="radio" class="form-check-input" name="capacity" id="" value="upto500">
                            <label class="form-check-label">
                                <br>  
                                <i class="fa fa-1x" aria-hidden="true"><h3>Up to 500 people</h3></i>
                            </label>
                        </div>
                        <%
                    }
                    %>
                <%
                    if(venues.getUpto1000() != null){
                        %>
                        <div class="form-check">
                            <input type="radio" class="form-check-input" name="capacity" id="" value="upto1000">
                            <label class="form-check-label">
                                <br>   
                                <i class="fa fa-1x" aria-hidden="true"><h3>Up to 1000 people</h3></i>
                            </label>
                        </div>
                        <%
                    }
                    %>
                <button class="btn-view">Book Venue</button>
            </form>
        </div>
    </body>
</html>

我需要从这个页面的数据库中检索项目

<%-- 
    Document   : MyEvents
    Created on : Jul 23, 2019, 11:17:46 AM
    Author     : Tariana
--%>

<%@page import="entities.Event"%>
<%@page import="java.util.Iterator"%>
<%@page import="java.util.List"%>
<%@page import="newpackage.Booking"%>
<%@page import="org.hibernate.Query"%>
<%@page import="org.hibernate.Session"%>
<%@page import="org.hibernate.service.ServiceRegistryBuilder"%>
<%@page import="entities.Users"%>
<%@page import="org.hibernate.cfg.Configuration"%>
<%@page import="org.hibernate.service.ServiceRegistry"%>
<%@page import="org.hibernate.SessionFactory"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%
    //checks whether there is a farmer account with a session within the system
    //this header spans over all the pages after the farmer has logged into the system
    if(session.getAttribute("mail") == null){
            out.println("<script type=\"text/javascript\">");
            out.println("alert('You need to login first!!');");
            out.println("window.location.href = \"/Eventer/Users/Login.jsp\";");
            out.println("</script>");
    }else{
        %>
        <html>
            <head>
                <%@include file="BookHeader.jsp" %>
                <title>My Events</title>
            </head>
            <body class="eventer">
                <div class="kadi">
            <%
                SessionFactory sessionFactory;
                ServiceRegistry serviceRegistry;

                Configuration configuration = new Configuration();
                configuration.addAnnotatedClass(Users.class)
                    .configure();

                serviceRegistry = new ServiceRegistryBuilder()
                        .applySettings(configuration.getProperties())
                        .configure("hibernate.cfg.xml")
                        .build();        
                sessionFactory = configuration.buildSessionFactory(serviceRegistry);

                Session sess = sessionFactory.openSession();
                String hql = "FROM Booking";
                Query queryy = sess.createQuery(hql);
                List<Booking> buying;
                List results = queryy.list();
                buying = results;
                Iterator<Booking> itr = buying.iterator();
                Users owner;
                Event venue;
                Booking event = new Booking();
                System.out.println();

                while(itr.hasNext()){
                    Booking g = itr.next();
                    event = g;

                    %>

                        <div class="card">
                            <img class="card-img-top" src="event.png" alt="">
                            <div class="card-body">
                                <h4 class="card-title"><%=event.getEventname()%></h4>
                                <p class="card-text">Date: <%=event.getDate()%></p>
                                <p class="card-text">Capacity for: <%=event.getCapacity()%></p>
                                <p class="card-text eve">ksh.<%=event.getPricing()%></p>
                                <form>
                                    <div class="form-group">
                                        <label class="sr-only" for="inputName">Hidden input label</label>
                                        <input type="text" class="form-control" name="inputName" id="inputName" placeholder="" value="" hidden>
                                        <button type="submit" class="btn-view">View Venue</button>
                                    </div>
                                </form>
                            </div>
                        </div>

                    <%
                }
            %>
                </div>
            </body>
        </html>
        <%
    }
%>

预订舱位

package newpackage;
// Generated Jul 23, 2019 11:11:55 AM by Hibernate Tools 4.3.1



/**
 * Booking generated by hbm2java
 */
public class Booking  implements java.io.Serializable {


     private Integer id;
     private String capacity;
     private String date;
     private String eventname;
     private String venue;
     private String owner;
     private int pricing;
     private String user;

    public Booking() {
    }

    public Booking(String capacity, String date, String eventname, String venue, String owner, int pricing, String user) {
       this.capacity = capacity;
       this.date = date;
       this.eventname = eventname;
       this.venue = venue;
       this.owner = owner;
       this.pricing = pricing;
       this.user = user;
    }

    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
    public String getCapacity() {
        return this.capacity;
    }

    public void setCapacity(String capacity) {
        this.capacity = capacity;
    }
    public String getDate() {
        return this.date;
    }

    public void setDate(String date) {
        this.date = date;
    }
    public String getEventname() {
        return this.eventname;
    }

    public void setEventname(String eventname) {
        this.eventname = eventname;
    }
    public String getVenue() {
        return this.venue;
    }

    public void setVenue(String venue) {
        this.venue = venue;
    }
    public String getOwner() {
        return this.owner;
    }

    public void setOwner(String owner) {
        this.owner = owner;
    }
    public int getPricing() {
        return this.pricing;
    }

    public void setPricing(int pricing) {
        this.pricing = pricing;
    }
    public String getUser() {
        return this.user;
    }

    public void setUser(String user) {
        this.user = user;
    }




}



我需要学习一种方法来比较对象或将对象更改回原来的对象状态

我想尝试一个将每个元素转换为字符串的 .tostring 方法,但它会引发一个问题,例如我存储类的问题,例如上述 POJO 类中的所有者,这将导致我目前面临的相同问题

【问题讨论】:

  • fromstring 方法是什么?
  • 请阅读“如何创建minimal reproducible example”。然后使用edit 链接改进您的问题(不要通过 cmets 添加更多信息)。否则我们无法回答您的问题并为您提供帮助。 “但它仍然不起作用”......不是一个有效的问题描述。您只发布了您的 Event 类,但 none 您的“测试”代码将实例化一个 Event、对其调用 toString() 或 fromstring() (无论首先实现该方法) .
  • 除此之外:您实际上想要做什么?将对象转换为特定的字符串格式(如 JSON)?或者您想发明自己的字符串格式,并使用它来(取消)持久化您的 Event 对象?
  • 这是问题开始的地方stackoverflow.com/questions/57165768/…
  • 所以我改为将所有映射文件转换为字符串,将类元素转换为字符串,以便持久性工作

标签: java string hibernate casting tostring


【解决方案1】:

您所指的过程称为序列化,是编程中的一个大主题。有几个库可以帮助您将类转换为 String 并返回。

我(和许多人)广泛使用的一个这样的库是 Jackson,一个 json 解析库:https://github.com/FasterXML/jackson 该库允许您编写以下代码:

public static String toString(Event event) {
    return new ObjectMapper().writeValueAsString(event);
}

public static Event fromString(String string) {
    return new ObjectMapper().readValue(string, Event.class);
}

我还看到你的类实现了Serializable。我会推荐上述方法而不是使用 java 内置序列化,因为 java 序列化存在几个问题。例如,如果你更改了你的类,序列化会在没有特别注意的情况下失败。

【讨论】:

  • 我似乎找不到 jar 文件的下载链接
  • 我使用的是可序列化的,因为我使用 hibernate 作为我的数据库,并且直接从数据库中创建了映射器和类
  • 链接上的绿色按钮带有“克隆或下载”文本,或者如果您使用的是 Maven 或 Gradle 等构建工具,则该项目存储在 Maven Central 中,以便于访问。跨度>
  • 链接未链接到库我必须从他们的网站下载所有 3 个库,但在实现 loc 时遇到以下问题
  • com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer 也没有发现创建 BeanSerializer 的属性(为避免异常,禁用 SerializationFeature .FAIL_ON_EMPTY_BEANS)(通过引用链:entities.Event["owner"]->entities.Users_$$_jvstad2_1["handler"])
【解决方案2】:

我不太确定你想用这个完成什么(尤其是“比较”部分)。 为什么要将对象转换为字符串?

但一般来说,您想要的不是“强制转换”(即将 unchanged 对象视为其他兼容类型),而是“序列化”(即将对象转换为可存储格式)。我猜想许多可用的 JSON 或 XML 序列化程序中的一个可以解决问题 - 再次取决于 为什么 你想这样做。

查看jacksongsonboonkryo 以了解可能满足您需求的示例库。

【讨论】:

  • 我需要使用 在我的网站上显示对象元素,但我已将其存储为字符串
猜你喜欢
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 2021-06-12
  • 1970-01-01
  • 1970-01-01
  • 2019-12-17
  • 2012-02-20
  • 1970-01-01
相关资源
最近更新 更多