简体   繁体   English

Hibernate无法将数据正确写入mysql

[英]Hibernate can not write data to mysql correctly

I am trying to write some information about the user who opens the web application which i made. 我正在尝试写一些有关打开我创建的Web应用程序的用户的信息。 The web app is simple. Web应用程序很简单。 When open it it shows users ip, user-agent, and the time of the last log into the app. 打开后,它会显示用户ip,用户代理以及上次登录应用程序的时间。 I`ve made this app with these technologies: Spring, Maven, Tomcat, Hibernate and MySQL. 我使用以下技术制作了该应用程序:Spring,Maven,Tomcat,Hibernate和MySQL。 It seems that everything is working correctly but when i open the app in browser in do note make a record to Data Base and i must start manually Main.java to make a record but the record is no correct because it does not record the real information but it record NULL everywhere. 似乎一切正常,但是当我在浏览器中打开应用程序时,请做一个记录到数据库,并且我必须手动启动Main.java来进行记录,但是该记录不正确,因为它没有记录真实信息但它到处都记录NULL。 I have two questions - How to do all this automatically (when i open the web app to have a record in DB) and Why my records are every time NULL. 我有两个问题-如何自动执行所有操作(当我打开Web应用程序以在DB中有记录时)以及为什么我的记录每次都是NULL时。

public class Main {

    public static void main(String[] args) {

        UserInfo user = new UserInfo();
        user.setRollNo(7);
        user.setIp(UserController.ip);
        user.setUserAgent(UserController.userAgent);
        user.setDate((Date) UserController.date);

        SessionFactory sessionFactory = new AnnotationConfiguration()
                .configure().buildSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        session.save(user);

        session.getTransaction().commit();
        session.close();
    }
}

UserController.java UserController.java

   @Controller
    public class UserController {

        public static String ip;
        public static String userAgent;
        public static Date date;

        @Autowired
        private HttpServletRequest request;

        @RequestMapping(value = "/connection")
        public ModelAndView getUserInfo() {

            ModelAndView modelandView = new ModelAndView("UserInfo");

            ip = request.getRemoteAddr();
            modelandView.addObject("msg1", "Your IP is " + ip);

            userAgent = request.getHeader("User-Agent");
            modelandView.addObject("msg2", "Your User agent is " + userAgent);

            date = new java.util.Date();
            /*
             * Calendar calendar = Calendar.getInstance(); java.sql.Date startDate =
             * new java.sql.Date(calendar.getTime() .getTime());
             */
            modelandView.addObject("msg3", "Your last log was at " + date);

            return modelandView;

        }

    }

UserInfo.java UserInfo.java

@Entity
@Table(name = "USER_INFORMATION")
public class UserInfo {

    @Id
    private int rollNo;
    private String ip;
    private String userAgent;
    private Date date;

    public int getRollNo() {
        return rollNo;
    }

    public void setRollNo(int rollNo) {
        this.rollNo = rollNo;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public String getUserAgent() {
        return userAgent;
    }

    public void setUserAgent(String userAgent) {
        this.userAgent = userAgent;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

}

hibernate.cfg.xml hibernate.cfg.xml

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/browserinfo</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>

        <property name="connection.pool_size">1</property>

        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <property name="show_sql">true</property>

        <property name="hbm2ddl.auto">validate</property>

        <mapping class="com.nikola.hellocontroller.UserInfo" />

    </session-factory>
</hibernate-configuration>

According to this: 根据这个:

@novy154 I am trying to make e record to DB with the users IP, user-agent info and the time when the user was lastloged in the app. @ novy154我正在尝试使用用户IP,用户代理信息和用户上次登录应用程序的时间来向数据库进行电子记录。 After that i want to display all records in the app. 之后,我想显示应用程序中的所有记录。

First of all, you need to have some DataAccessLayer. 首先,您需要具有一些DataAccessLayer。 Something like 就像是

public interface UserInfoRepository {
    void save(UserInfo userInfo);
    Collection<UserInfo> findAll();
}

and it's implementation. 及其实现。

Then maybe some service over the Repository, but it doesn't matter in this case, so let's skip it. 然后可能在存储库上提供一些服务,但是在这种情况下没有关系,因此让我们跳过它。

You need to inject your repository into controller and: 您需要将存储库注入控制器,并:

1) invoke userInfoRepository.save(newlyCreatedUserInfo) 1)调用userInfoRepository.save(newlyCreatedUserInfo)

2) pass all UserInfos to your view (by invoking userInfoRepository.findAll() and putting the result in modelAndView) and display it somehow. 2)将所有UserInfo传递到您的视图(通过调用userInfoRepository.findAll()并将结果放入modelAndView中)并以某种方式显示它。

Let me know if you need help implementing this. 让我知道您是否需要帮助来实现此目的。

But this is just in purpose of learning how to make simple crud-like application, cause this doesn't make any sense. 但这只是为了学习如何制作简单的类应用程序,因为这没有任何意义。 You can't even identify your user, you just want to track each visitor's ip, user info and so on. 您甚至无法识别您的用户,您只想跟踪每个访问者的ip,用户信息等。

// edit: Repository implementation would be something like: //编辑:存储库实现将类似于:

@Repository
@Transactional
public class UserInfoRepositoryImpl implements UserInfoRepository {

    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void save(UserInfo userInfo) {
        getCurrentSession.save(userInfo);
    }

    @Override
    public Collection<UserInfo> findAll() {

        final Criteria root = getCurrentSession().createCriteria(UserInfo.class);
        return Collections.checkedList(root.list(), UserInfo.class);
    }

    private Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }
}

Then in your controller method you need to invoke save(newlyCreatedUserInfo) to store your info in the database and 然后,在控制器方法中,您需要调用save(newlyCreatedUserInfo)将信息存储在数据库中,然后

modelAndView.addObject("userInfos", repository.findAll());

to retrieve all data and pass it to a view. 检索所有数据并将其传递给视图。

Of course remember about 当然要记住

...
@Autowired
private UserInfoRepository userInfoRepository;
...

in controller. 在控制器中。

Note that since spring-data-jpa provides you more powerful repositories out of the box, this is reinventing a wheel. 请注意,由于spring-data-jpa可以为您提供更强大的存储库,因此,这是在重新设计轮子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM