问:
How to save video into file which i get from POST request method?
I am writing a Python backend for an Android app with Flask. I get video from POST method (when I do this: print(request.files['video'].read()) I get "d3\xb9}\xff\x04\xa4M\xef\x8fS\xc1\xf0\x9e:|ge\x1cfO\xc1\x11ry\x0b\xea\xd1\x82\xf2\xa9-H..."). I can convert it to numpy array by doing this np.frombuffer(request.files['video'].read(), np.uint8), but I don't know what to do next to save video to file in mp4 format. Can you please help me?

答:
No need for you to read the file, if you just want to save the video as a file.

You can use the method provided by Flask's documentation. It provides a guideline on how to handle files. Link is here: https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/

Or you can use an extension called "Flask-Uploads", which enable you to handle file uploading in a convenient way.

Here is an example:

from flask_uploads import UploadSet
from werkzeug.utils import secure_filename

media = UploadSet('media', ('mp4')) # Create an upload set that only allow mp4 file
....
@app.route('/upload/', methods=["POST"])
def upload():
    if "video" in request.files:
        video = request.files["video"]
        filename = secure_filename(file.filename) # Secure the filename to prevent some kinds of attack
        media.save(video, name=filename)
        # Video saved
```

For detailed documentation of Flask-Uploads, check it out here: https://pythonhosted.org/Flask-Uploads/

Body:
No need for you to read the file, if you just want to save the video as a file.

You can use the method provided by Flask's documentation. It provides a guideline on how to handle files. Link is here: https://flask.palletsprojects.com/en/1.1.x/patterns/fileuploads/

Or you can use an extension called "Flask-Uploads", which enable you to handle file uploading in a convenient way.

Here is an example:

from flask_uploads import UploadSet
from werkzeug.utils import secure_filename

media = UploadSet('media', ('mp4')) # Create an upload set that only allow mp4 file
....
@app.route('/upload/', methods=["POST"])
def upload():
    if "video" in request.files:
        video = request.files["video"]
        filename = secure_filename(file.filename) # Secure the filename to prevent some kinds of attack
        media.save(video, name=filename)
        # Video saved

For detailed documentation of Flask-Uploads, check it out here: https://pythonhosted.org/Flask-Uploads/


来源: stackexchange

问:
debug=true in web.config = BAD thing?
We're seeing lots of virtual memory fragmentation and out of memory errors and then it hits the 3GB limit.

The compilation debug is set to true in the web.config but I get different answers from everyone i ask, does debug set to true cause each aspx to compile into random areas of ram thus fragmenting that ram and eventually causing out of memory problems?

答:
AFAIK "debug = true" not cause the situation you mentioned.

I had faced same problem with an ASP.NET application that created images on the fly.

so I think you have a problem with not disposed resources.

If you deploy your aspx files with code-behind files to server. It will be compiled once when the request comes to an aspx. then it will be stored to the cache until the file changes.

OwnerDisplayName: MateloT

LastEditorDisplayName: ScarletGarden

ContentLicense: CC BY-SA 2.5

Title: debug=true in web.config = BAD thing?

OwnerDisplayName: ScarletGarden


问:
mapDispatchToProps working, but dispatched action does not fire off in onClick
Pretty green to React and Redux still. I have been running in circles trying to solve this problem, so I'm breaking down and posting this question. I actually had this working yesterday, and now I can't figure out what I've done to skrew it up.

The issue is that the createUser() action in the onClick event of the RegistrationButton does not seem to be dispatching. The onClick function is firing, but createUser never fires off.

It's got to be something small. Thanks for taking a look.

```<code>import React, { Component } from "react";
import { connect } from "react-redux";
import "../../App.css";
import { nextStep, createUser } from "../../actions/registrationActions";

class RegistrationButton extends Component {
  render() {
    switch (this.props.step) {
      default:
      case 1:
      case 2:
        return (
          <button className="submit-reg-form-btn" onClick={this.props.nextStep}>
            Continue
          </button>
        );
      case 3:
        return (
          <button
            className="submit-reg-form-btn"
            onClick={(e) => {
              e.preventDefault();
              this.props.createUser({
                username: this.props.username,
                email: this.props.email,
                password: this.props.password,
                name:
                  String(this.props.firstname) +
                  " " +
                  String(this.props.lastname),
                birthdate: this.props.birthdate,
                gender: this.props.gender,
                preferredGender: this.props.preferredGender,
                liability: Boolean(this.props.liability),
                bio: this.props.bio,
                role: this.props.role,
                karma: this.props.karma,
                mentalState: this.props.mentalState,
              });
            }}
          >
            Complete Registration
          </button>
        );
    }
  }
}

const mapStateToProps = (state) => {
  const { registration } = state;
  return {
    step: registration.registrationStep,
    firstname: registration.firstname,
    lastname: registration.lastname,
    username: registration.username,
    email: registration.email,
    password: registration.password,
    birthdate: registration.birthdate,
    gender: registration.gender,
    preferredGender: registration.preferredGender,
    liability: registration.liability,
    mentalState: registration.mentalState,
    role: registration.role,
    bio: registration.bio,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    nextStep: (e) => {
      e.preventDefault();
      dispatch(nextStep());
    },
    createUser: (user) => {
      dispatch(createUser(user));
    },
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(RegistrationButton);

</code>```

```<code>registrationActions.js

import axios from "axios";
import {
  SET_ERROR,
  REGISTRATION_SUCCESS,
  ...
} from "./types";

export const createUser = (user) => (dispatch) => {
  axios.post("/api/createUser", user).then((res) => {
    if (res.data.error !== "") {
      dispatch({
        type: SET_ERROR,
        payload: "failed to create user",
      });
    } else {
      dispatch({
        type: REGISTRATION_SUCCESS,
      });
    }
  });
};
....
....
</code>```

```<code>registrationReducer.js

import {
  SHOW_REGISTRATION_STEP_1,
  SHOW_REGISTRATION_STEP_2,
  SHOW_REGISTRATION_STEP_3,
  NEXT_REGISTRATION_STEP,
  REGISTRATION_SUCCESS,
  SET_FIRST_NAME,
  SET_LAST_NAME,
  SET_USERNAME,
  SET_USER_EMAIL,
  SET_USER_PASSWORD,
  SET_USER_BIRTHDATE,
  SET_USER_GENDER,
  SET_PREFERRED_GENDER,
  SET_USER_LIABILITY,
  SET_USER_MENTAL_STATE,
  SET_USER_ROLE,
  SET_USER_BIO,
  SET_ERROR,
} from "../actions/types";

const initialState = {
  registrationStep: 1,
  error: "",
  registrationComplete: false,
  firstname: "",
  lastname: "",
  username: "",
  email: "",
  password: "",
  birthdate: "",
  gender: "",
  preferredGender: "",
  liability: "",
  mentalState: "",
  role: "",
  bio: "",
};

export default function (state = initialState, action) {
  switch (action.type) {
    case SHOW_REGISTRATION_STEP_1:
      return {
        ...state,
        registrationStep: 1,
      };
    case SHOW_REGISTRATION_STEP_2:
      return {
        ...state,
        registrationStep: 2,
      };
    case SHOW_REGISTRATION_STEP_3:
      return {
        ...state,
        registrationStep: 3,
      };
    case REGISTRATION_SUCCESS:
      return {
        ...state,
        error: "",
        registrationStep: 4,
        registrationComplete: true,
      };
    case SET_ERROR:
      return {
        ...state,
        error: action.payload,
      };
    ...
    ...
    default:
      return { ...state };
  }
}
</code>```

```<code>reducers/index.js

import { createStore, applyMiddleware, combineReducers } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import ReduxThunk from "redux-thunk";
import authReducer from "./authReducer";
import errorReducer from "./errorReducer";
import registrationReducer from "./registrationReducer";

const rootReducer = combineReducers({
  auth: authReducer,
  errors: errorReducer,
  registration: registrationReducer,
});

export const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(ReduxThunk))
);

</code>```

答:
This is the line that breaks your code

```<code> onClick={this.props.createUser({
</code>```

You are, in fact, calling the method when the component mounts. What you actually need to do is this

```<code> onClick={() => this.props.createUser({
</code>```

And you might not need to treat the "e.preventDefault()" event after that, neither.

LE (following updated question)
Use the

```<code>bindActionCreators
</code>```

method from redux to wrap your action creators. final version could look like this

```<code>const mapDispatchToProps = (dispatch) => bindActionCreators({
createUser,
nextStep,
}, dispatch)
</code>```

Hope that helps. Cheers.

ContentLicense: CC BY-SA 4.0

Body:
Pretty green to React and Redux still. I have been running in circles trying to solve this problem, so I'm breaking down and posting this question. I actually had this working yesterday, and now I can't figure out what I've done to skrew it up.

The issue is that the createUser() action in the onClick event of the RegistrationButton does not seem to be dispatching. The onClick function is firing, but createUser never fires off.

It's got to be something small. Thanks for taking a look.

import React, { Component } from "react";
import { connect } from "react-redux";
import "../../App.css";
import { nextStep, createUser } from "../../actions/registrationActions";

class RegistrationButton extends Component {
  render() {
    switch (this.props.step) {
      default:
      case 1:
      case 2:
        return (
          <button className="submit-reg-form-btn" onClick={this.props.nextStep}>
            Continue
          </button>
        );
      case 3:
        return (
          <button
            className="submit-reg-form-btn"
            onClick={(e) => {
              e.preventDefault();
              this.props.createUser({
                username: this.props.username,
                email: this.props.email,
                password: this.props.password,
                name:
                  String(this.props.firstname) +
                  " " +
                  String(this.props.lastname),
                birthdate: this.props.birthdate,
                gender: this.props.gender,
                preferredGender: this.props.preferredGender,
                liability: Boolean(this.props.liability),
                bio: this.props.bio,
                role: this.props.role,
                karma: this.props.karma,
                mentalState: this.props.mentalState,
              });
            }}
          >
            Complete Registration
          </button>
        );
    }
  }
}

const mapStateToProps = (state) => {
  const { registration } = state;
  return {
    step: registration.registrationStep,
    firstname: registration.firstname,
    lastname: registration.lastname,
    username: registration.username,
    email: registration.email,
    password: registration.password,
    birthdate: registration.birthdate,
    gender: registration.gender,
    preferredGender: registration.preferredGender,
    liability: registration.liability,
    mentalState: registration.mentalState,
    role: registration.role,
    bio: registration.bio,
  };
};

const mapDispatchToProps = (dispatch) => {
  return {
    nextStep: (e) => {
      e.preventDefault();
      dispatch(nextStep());
    },
    createUser: (user) => {
      dispatch(createUser(user));
    },
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(RegistrationButton);

registrationActions.js

import axios from "axios";
import {
  SET_ERROR,
  REGISTRATION_SUCCESS,
  ...
} from "./types";

export const createUser = (user) => (dispatch) => {
  axios.post("/api/createUser", user).then((res) => {
    if (res.data.error !== "") {
      dispatch({
        type: SET_ERROR,
        payload: "failed to create user",
      });
    } else {
      dispatch({
        type: REGISTRATION_SUCCESS,
      });
    }
  });
};
....
....

registrationReducer.js

import {
  SHOW_REGISTRATION_STEP_1,
  SHOW_REGISTRATION_STEP_2,
  SHOW_REGISTRATION_STEP_3,
  NEXT_REGISTRATION_STEP,
  REGISTRATION_SUCCESS,
  SET_FIRST_NAME,
  SET_LAST_NAME,
  SET_USERNAME,
  SET_USER_EMAIL,
  SET_USER_PASSWORD,
  SET_USER_BIRTHDATE,
  SET_USER_GENDER,
  SET_PREFERRED_GENDER,
  SET_USER_LIABILITY,
  SET_USER_MENTAL_STATE,
  SET_USER_ROLE,
  SET_USER_BIO,
  SET_ERROR,
} from "../actions/types";

const initialState = {
  registrationStep: 1,
  error: "",
  registrationComplete: false,
  firstname: "",
  lastname: "",
  username: "",
  email: "",
  password: "",
  birthdate: "",
  gender: "",
  preferredGender: "",
  liability: "",
  mentalState: "",
  role: "",
  bio: "",
};

export default function (state = initialState, action) {
  switch (action.type) {
    case SHOW_REGISTRATION_STEP_1:
      return {
        ...state,
        registrationStep: 1,
      };
    case SHOW_REGISTRATION_STEP_2:
      return {
        ...state,
        registrationStep: 2,
      };
    case SHOW_REGISTRATION_STEP_3:
      return {
        ...state,
        registrationStep: 3,
      };
    case REGISTRATION_SUCCESS:
      return {
        ...state,
        error: "",
        registrationStep: 4,
        registrationComplete: true,
      };
    case SET_ERROR:
      return {
        ...state,
        error: action.payload,
      };
    ...
    ...
    default:
      return { ...state };
  }
}

reducers/index.js

import { createStore, applyMiddleware, combineReducers } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import ReduxThunk from "redux-thunk";
import authReducer from "./authReducer";
import errorReducer from "./errorReducer";
import registrationReducer from "./registrationReducer";

const rootReducer = combineReducers({
  auth: authReducer,
  errors: errorReducer,
  registration: registrationReducer,
});

export const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(ReduxThunk))
);

Body:
This is the line that breaks your code

 onClick={this.props.createUser({

You are, in fact, calling the method when the component mounts. What you actually need to do is this

 onClick={() => this.props.createUser({

And you might not need to treat the "e.preventDefault()" event after that, neither.

LE (following updated question)
Use the

bindActionCreators

method from redux to wrap your action creators. final version could look like this

const mapDispatchToProps = (dispatch) => bindActionCreators({
createUser,
nextStep,
}, dispatch)

Hope that helps. Cheers.


问:
How to extract the last digits of strings using regular expressions?
I have a bunch of colnames

```<code>L_1_3
L_2_23
L_3_91
L_3_16
</code>```

I want to replace these colnames with new names using the last digits following the _ like this:

```<code>3
23
91
16
</code>```

I've tried colnames(X) <- gsub("L_\\d\\d_", "", colnames(X)) which works for strings with double digits at the end. I want one that works for both single and double digits.

Thank you!

Body:
I have a bunch of colnames

L_1_3
L_2_23
L_3_91
L_3_16

I want to replace these colnames with new names using the last digits following the _ like this:

3
23
91
16

I've tried colnames(X) <- gsub("L_\\d\\d_", "", colnames(X)) which works for strings with double digits at the end. I want one that works for both single and double digits.

Thank you!

Body:
Tried to keep it as simple as possible

sub(".*_(\\d+$)", "\\1", X)
[1] "3"  "23" "91" "16"


问:
Identifier not found error when accessing Template Class Member from Sub-Class
This is my very first question on StackOverflow. I've searched for similar "Identifier not Found" errors but couldn't find anything helpful. I'll be grateful for your help since I've been trying to work this out for 2 hours with no results.

It basically creates an object of type "Addition" and prints "1 + 1 = 2" (if it worked).

When I was not using templates it was working fine. But when I changed everything to templates it stopped working. I couldn't figure this out.

Visual studio does not underline anything in red, however I get a "identifier not defined" error for m_Argument_1 and m_Argument_2.

Thank you for your help and I apologize if this is a too simple question to ask here, but nevertheless I couldn't find a way out or figure out where the problem is.

This is my header file "Expression.h":

```<code>#ifndef OPERATION_HEADER
#define OPERATION_HEADER

#include <string>
#include <iostream>

template <typename T>
class Expression
{
protected:

    char m_ExpressionSign; /* Represents Expression's Sign ('+','-','*','/') */

    T m_Argument_1; /* Represents L Argument */
    T m_Argument_2; /* Represents R Argument */

public:

    Expression(T arg_1, T arg_2, char expressionSign) : m_Argument_1(arg_1), m_Argument_2(arg_2), m_ExpressionSign(expressionSign) { };

    virtual T Result() const = 0;

    virtual void Print(std::ostream& out) const;

    friend std::ostream& operator << (std::ostream& out, const Expression<T>& expression);
};

template <typename T>
class Addition : public Expression<T>
{
public:
    Addition(T arg1, T arg2) : Expression<T>(arg1, arg2, '+') {};
    T Result() const { return m_Argument_1 + m_Argument_2; };
};

template <typename T>
void Expression<T>::Print(std::ostream& out) const
{
    out << m_Argument_1 << " " << m_ExpressionSign << " " << m_Argument_2 << " = ";
}

template <typename T>
std::ostream& operator << (std::ostream& out, const Expression<T>& expression)
{
    expression.Print(out);
    return out;
}

#endif /* OPERATION_HEADER */
</code>```

And this is my main.cpp:

```<code>#include <iostream>
#include <iomanip>

#include "Expression.h"

int main(int argc, char** argv)
{
    Addition<int> A2(1, 1);

    std::cout << "A2: " << A2 << " = " << std::setw(2) << A2.Result() << std::endl;
    retun 0;
}
</code>```

答:
When inheriting from a class template, identifiers need to be qualified so that the compiler knows where they come from. In this case, in the definition of Addition, you could do:

```<code>T Result() const { return this->m_Argument_1
                        + this->m_Argument_2; };
</code>```

Alternatively, you could qualify the names like this:

```<code>T Result() const { return Expression<T>::m_Argument_1
                        + Expression<T>::m_Argument_2; };
</code>```

Body:
This is my very first question on StackOverflow. I've searched for similar "Identifier not Found" errors but couldn't find anything helpful. I'll be grateful for your help since I've been trying to work this out for 2 hours with no results.

It basically creates an object of type "Addition" and prints "1 + 1 = 2" (if it worked).

When I was not using templates it was working fine. But when I changed everything to templates it stopped working. I couldn't figure this out.

Visual studio does not underline anything in red, however I get a "identifier not defined" error for m_Argument_1 and m_Argument_2.

Thank you for your help and I apologize if this is a too simple question to ask here, but nevertheless I couldn't find a way out or figure out where the problem is.

This is my header file "Expression.h":

#ifndef OPERATION_HEADER
#define OPERATION_HEADER

#include <string>
#include <iostream>

template <typename T>
class Expression
{
protected:

    char m_ExpressionSign; /* Represents Expression's Sign ('+','-','*','/') */

    T m_Argument_1; /* Represents L Argument */
    T m_Argument_2; /* Represents R Argument */

public:

    Expression(T arg_1, T arg_2, char expressionSign) : m_Argument_1(arg_1), m_Argument_2(arg_2), m_ExpressionSign(expressionSign) { };

    virtual T Result() const = 0;

    virtual void Print(std::ostream& out) const;

    friend std::ostream& operator << (std::ostream& out, const Expression<T>& expression);
};

template <typename T>
class Addition : public Expression<T>
{
public:
    Addition(T arg1, T arg2) : Expression<T>(arg1, arg2, '+') {};
    T Result() const { return m_Argument_1 + m_Argument_2; };
};

template <typename T>
void Expression<T>::Print(std::ostream& out) const
{
    out << m_Argument_1 << " " << m_ExpressionSign << " " << m_Argument_2 << " = ";
}

template <typename T>
std::ostream& operator << (std::ostream& out, const Expression<T>& expression)
{
    expression.Print(out);
    return out;
}

#endif /* OPERATION_HEADER */

And this is my main.cpp:

#include <iostream>
#include <iomanip>

#include "Expression.h"

int main(int argc, char** argv)
{
    Addition<int> A2(1, 1);

    std::cout << "A2: " << A2 << " = " << std::setw(2) << A2.Result() << std::endl;
    retun 0;
}

Body:
When inheriting from a class template, identifiers need to be qualified so that the compiler knows where they come from. In this case, in the definition of Addition, you could do:

T Result() const { return this->m_Argument_1
                        + this->m_Argument_2; };

Alternatively, you could qualify the names like this:

T Result() const { return Expression<T>::m_Argument_1
                        + Expression<T>::m_Argument_2; };


问:
Use of GUIDs as id in public facing data integration web service
To put the question into some context, the system exposing the web service uses GUIDs internally as identifiers for all entities.

In such case, when designing a public facing data integration web service (used mainly for importing or exporting data from the system to other, external systems), what would you consider as pros and cons of using the internal identifiers in the interface of the service?

With such solution, the export methods of the web service would return the dto's identified with GUIDs and the import methods would accept similar dto's - I assume the external system would be responsible for generating new GUIDs for new entities.

What are the potential issues one might face with this approach?

The technology stack for the system and web service is .NET / WCF / SOAP

答:
First, let's look at the more generic "how do I set up a public API" question, my first exercise is determining what information is needed by the consumer of the service. I also look and see if there are is company specific naming in the object model. I then create a service model (data contract, if you want WCF specific) that matches the view I want to show the consumer. This includes a unique key, which is more often a SKU string (human readable key) than a GUID/int (the actual derived primary key), as the SKU is public and the means of storing in the database is not. So, in general, I would not expose these primary key concepts, if that is what the GUID is.

Now to the question of "do you see problems with this approach". I will focus on more general concepts so you can make a more informed decision, as there is no 100% right/wrong answer.

As long as this is machine to machine and the use of the GUID is something both systems are aware of, I see nothing particularly scary about this approach. If this ultimate goes to a human readable system where the GUID has to be interacted with, then you have an issue.

One potential issue with the system is exposing your own primary key information to customer or client systems, who don't have to understand this level of detail. If this is actually "semi-public" with a select list of vendors, the "risk" might be less. This is the primary issue I see.

One could argue the weight of the GUID (128 bits) versus a smaller identifier, but this is a bogus answer, IMO, as the network latency more than outweighs sending a few more bytes as a request parameter.

ContentLicense: CC BY-SA 3.0


答:
You should use .then,</p>

```<code>console.log(price_data()) // This will return promise
price_data().then((data) => {
console.log(data); // This will contain the final return value from the promise axios.then.
});
</code>```

Title: Return Axios data so I can use it

Body:
I am pulling some data from a local API I made for testing, and need to use the resulting data outside of the function. I am new to JS and am having trouble working with Promises.
Here is my code:

const axios = require('axios').default;

function price_data () {
    return axios.post('http://127.0.0.1:8000/api/token/', {
      username: 'parke',
      password: 'password'
    })
    .then(function (response) {
      var token = response['data']['access'];
      return axios.get('http://127.0.0.1:8000/price', {
      headers:{'Authorization': 'Bearer ' + token}
    })
      .then(function (response) {
        var all_data = []
        for (i = 0; i < response['data'].length; i ++) {
          all_data.push(response['data'][i]['close'])
        }
        console.log(all_data);
        return(all_data)
      })
      .catch(function (error) {
        console.log(error)
    })
    .catch(function (error) {
      console.log(error);
    })
    })
}
console.log(price_data())

The result looks like this:

Promise { <pending> }
[
       1,      1,      1,      1,      1,      1,      1, 1.5907,
  1.5318, 1.5318, 1.5907, 1.5907, 1.5907, 1.5907, 1.5907, 1.5318,
  1.3551,  1.414,  1.414,  1.414,  1.414, 1.3551, 1.2372, 1.2372,
   1.414,  1.414, 1.3551,  1.414,  1.414,  1.414,  1.414,  1.414,
   1.414,  1.414,  1.414,  1.414,  1.414, 1.2961, 1.2961, 1.2961,
   1.414,  1.414,  1.414,  1.414,  1.414, 1.3551, 1.3551, 1.3551,
  1.3551, 1.3551, 1.3551, 1.3551, 1.3551, 1.2961, 1.2961, 1.2961,
  1.2961, 1.2961, 1.2961, 1.2961, 1.3551, 1.2961, 1.2961, 1.3551,
   1.414,  1.414,  1.414, 1.4729, 1.4729, 1.4729, 1.4729, 1.4729,
  1.4729,  1.414,  1.414,  1.414,  1.414,  1.414,  1.414,  1.414,
   1.414,  1.414, 1.4729, 1.4729, 1.4729, 1.4729, 1.4729, 1.4729,
  1.4729, 1.4729, 1.5907, 1.5613, 1.5907, 1.5465,  1.576, 1.5318,
  1.5318, 1.5539, 1.5907, 1.5907,
  ... 1101 more items
]

I kinda understand that the function is returning before the console.log prints, but I need to get that data that is being logged outside of the function. It would be greatly appreciated if someone could help me out real quick. Thanks!

Body:
You should use .then,

console.log(price_data()) // This will return promise
price_data().then((data) => {
console.log(data); // This will contain the final return value from the promise axios.then.
});


问:
authentication log in form with jwt and react
I have made and fetched a Login form with JWT and react. I managed to fetched the data for the username and password and everything works perfectly but then I want to redirect the user to a new page when he clicks on submit and I have no idea how to do that. I'm also using react router. Any help will be welcome

import React, { Component } from "react";
import axios from "axios";

export default class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            username: "test",
            password: "test",
        }
    }

    handleChange = (e) => {
        this.setState({
            [e.target.name]: e.target.value,
        })
    }

    login = () => {
        const {username, password} = this.state;

        axios(`/users/login`, {
          method: "POST",
          data: {
              username,
              password,
          }
        })
        .then(response => {
            localStorage.setItem('token', response.data.token);
            console.log(response);
        })
        .catch(error => {
            console.log(error)
        })

     }

    render() {
        return (

Sign In

                    Username
                    <input type="username" className="form-control" placeholder="Enter username" name="username" value={this.state.username} onChange={this.handleChange} />

                    Password
                    <input type="password" className="form-control" placeholder="Enter password" name="password" value={this.state.password} onChange={this.handleChange} />

                        <input type="checkbox" className="custom-control-input" id="customCheck1"  />
                        Remember me

                <button type="submit" className="btn btn-primary btn-block" onClick={this.login}>Submit</button>

                    Forgot password?

        );

}
} ```

答:
import withRouter import {withRouter} from 'react-router-dom';

remove export before class Login class Login extends Component {...

export class at the end of the file: export default withRouter(Login);

and use react-router-dom:

```<code>axios(`/users/login`, {
    //...
})
.then(response => {
    localStorage.setItem('token', response.data.token);
    console.log(response);
    this.props.history.push('/url');
})
//...
</code>```

Body:
import withRouter import {withRouter} from 'react-router-dom';

remove export before class Login class Login extends Component {...

export class at the end of the file: export default withRouter(Login);

and use react-router-dom:

axios(`/users/login`, {
    //...
})
.then(response => {
    localStorage.setItem('token', response.data.token);
    console.log(response);
    this.props.history.push('/url');
})
//...


问:
Best practices for auto increment a number EF Core
I'm looking for best practices in order to increment some numbers in my DB using EF Core..

I have a DB model called PARENT. In my application, I can have several PARENTS. Each PARENT has several CHILDS.

PARENT1: CHILD1 - CHILD2

PARENT2: CHILD1 - CHILD2 - CHILD3

I want, inside each PARENT, each children be numbered incrementally by a column: int Number. This means,

PARENT1.CHILD1 = 001;

PARENT1.CHILD2 = 002;

PARENT2.CHILD1 = 001;

PARENT2.CHILD2 = 002;

...

So, it has to be only unique and incremented by parent..

Can anyone give me some best practices in order to achieve this in an efficient way?

UPDATE:

```<code>public class Bar {
    public Guid BarId {get;set;}
    public ICollection<Client> Clients {get;set;}
}

public class Client {
    public Guid ClientId {get;set;}
    public Guid BarId {get;set;}
    public int ClientNumber {get;set;}
}

public class Context : DBContext {
    entity.HasKey(e => new { e.BarId, e.ClientId }).HasName("PK_CLIENT");
                entity.Property(e => e.ClientId).ValueGeneratedWhenDefault();
    entity.Property(e => e.ClientNumber).ValueGeneratedOnAdd();
    entity.HasIndex(e => new {e.BarId, e.ClientNumber}).IsUnique()
        .HasName("IX_CLIENT_NUMBER");
}
</code>```

By calling ValueGeneratedOnAdd() I make the number column increment, but I want it to increment for each Bar, so it should allow duplicated client numbers between different bars, but not at the same Bar, and also increment them by Bar, not just by the Client entity.

答:
Maybe it is not what you want, but since I'm writing some code, it does not fit as a comment.

To set the ClientNumber in child compositions, I would write some code like this:

```<code>Bar bar = new Bar();
int seq = 1;
bar.Clients.Add(new Client() { ClientNumber = seq++; });
bar.Clients.Add(new Client() { ClientNumber = seq++; });
dbContext.Update(bar);
dbContext.SaveChanges();
</code>```

It works fine when you are creating a new Bar. If it can be edited and clients can be added or removed from the bar - like a CRUD -, then you have to change somethings. But it shows what I was talking about in the comment (setting the ClientNumber).

Another approach would be to intercept the SaveChanges, which I would avoid in this case, because it is kind of unclear for unadvised developers:

```<code>public class DbContextWithBlackMage : DbContext
{
    public override int SaveChanges(bool acceptAllChangesOnSuccess)
    {
        OnBeforeSaving();
        return base.SaveChanges(acceptAllChangesOnSuccess);
    }

    private void OnBeforeSaving()
    {
        var entries = ChangeTracker.Entries();
        foreach (var entry in entries)
        {
            //TODO black mage to fill the ClientNumber very secretly and obscurely
            //TODO Matheus will be angry when he finds out muahahahahaha!
        }
    }
}
</code>```

Anyways... it is probably not what you want, but maybe it will inspire will about how to solve it (or how do not).

Body:
I'm looking for best practices in order to increment some numbers in my DB using EF Core..

I have a DB model called PARENT. In my application, I can have several PARENTS. Each PARENT has several CHILDS.

PARENT1: CHILD1 - CHILD2

PARENT2: CHILD1 - CHILD2 - CHILD3

I want, inside each PARENT, each children be numbered incrementally by a column: int Number. This means,

PARENT1.CHILD1 = 001;

PARENT1.CHILD2 = 002;

PARENT2.CHILD1 = 001;

PARENT2.CHILD2 = 002;

...

So, it has to be only unique and incremented by parent..

Can anyone give me some best practices in order to achieve this in an efficient way?

UPDATE:

public class Bar {
    public Guid BarId {get;set;}
    public ICollection<Client> Clients {get;set;}
}

public class Client {
    public Guid ClientId {get;set;}
    public Guid BarId {get;set;}
    public int ClientNumber {get;set;}
}

public class Context : DBContext {
    entity.HasKey(e => new { e.BarId, e.ClientId }).HasName("PK_CLIENT");
                entity.Property(e => e.ClientId).ValueGeneratedWhenDefault();
    entity.Property(e => e.ClientNumber).ValueGeneratedOnAdd();
    entity.HasIndex(e => new {e.BarId, e.ClientNumber}).IsUnique()
        .HasName("IX_CLIENT_NUMBER");
}

By calling ValueGeneratedOnAdd() I make the number column increment, but I want it to increment for each Bar, so it should allow duplicated client numbers between different bars, but not at the same Bar, and also increment them by Bar, not just by the Client entity.

Body:
Maybe it is not what you want, but since I'm writing some code, it does not fit as a comment.

To set the ClientNumber in child compositions, I would write some code like this:

Bar bar = new Bar();
int seq = 1;
bar.Clients.Add(new Client() { ClientNumber = seq++; });
bar.Clients.Add(new Client() { ClientNumber = seq++; });
dbContext.Update(bar);
dbContext.SaveChanges();

It works fine when you are creating a new Bar. If it can be edited and clients can be added or removed from the bar - like a CRUD -, then you have to change somethings. But it shows what I was talking about in the comment (setting the ClientNumber).

Another approach would be to intercept the SaveChanges, which I would avoid in this case, because it is kind of unclear for unadvised developers:

public class DbContextWithBlackMage : DbContext
{
    public override int SaveChanges(bool acceptAllChangesOnSuccess)
    {
        OnBeforeSaving();
        return base.SaveChanges(acceptAllChangesOnSuccess);
    }

    private void OnBeforeSaving()
    {
        var entries = ChangeTracker.Entries();
        foreach (var entry in entries)
        {
            //TODO black mage to fill the ClientNumber very secretly and obscurely
            //TODO Matheus will be angry when he finds out muahahahahaha!
        }
    }
}

Anyways... it is probably not what you want, but maybe it will inspire will about how to solve it (or how do not).


问:
How to convert the Object[] to String[] in Java?
I have a question about Java. I have an Object[] (Java default, not the user-defined) and I want to convert it to a String[]. Can anyone help me? thank you.

答:
Java 8 solution:</p>

```<code>String[] strArr = Arrays.stream(objArr).map(Object::toString).toArray(String[]::new);
</code>```

Body:
Java 8 solution:

String[] strArr = Arrays.stream(objArr).map(Object::toString).toArray(String[]::new);


答:
To onClick property you should provide function itself, not calling her as you did

Right way is

```<code>onClick={() => this.props.createUser(
</code>```

or

```<code>onClick={this.props.createUser.bind(null, yourParam)}
</code>```

Title: mapDispatchToProps working, but dispatched action does not fire off in onClick

Body:
To onClick property you should provide function itself, not calling her as you did

Right way is

onClick={() => this.props.createUser(

or

onClick={this.props.createUser.bind(null, yourParam)}


问:
Find optimal Lasso/L1 regularization strength using cross validation for logistic regression in scikit learn
For my logistic regression model, I would like to evaluate the optimal L1 regularization strength using cross validation (eg: 5-fold) in place of a single test-train set as shown below in my code:

```<code>from sklearn.model_selection import train_test_split
train_x, test_x, train_y, test_y = train_test_split(X_scaled,y, stratify=y, test_size=0.3,
   random_state=2)

#Evaluate L1 regularization strengths for reducing features in final model
C = [10, 1, .1, 0.05,.01,.001] # As C decreases, more coefficients go to zero

for c in C:
    clf = LogisticRegression(penalty='l1', C=c, solver='liblinear', class_weight="balanced")
    clf.fit(train_x, train_y)
    pred_y=clf.predict(test_x)
    print("Model performance with Inverse Regularization Parameteter, C = 1/λ VALUE: ", c)
    cr=metrics.classification_report(test_y, pred_y)
    print(cr)
    print('')
</code>```

Can somebody show me how to do this over 5-distinct test-train sets using cross-validation (i.e., without replicating the above code 5-times and distinct random states)?

答:
Actually, classification_report as a metric is not defined as a scoring metric inside sklearn.model_selection.cross_val_score. So, I will use f1_micro instead in the following code:

```<code>from sklearn.model_selection import cross_val_score

#Evaluate L1 regularization strengths for reducing features in final model
C = [10, 1, .1, 0.05,.01,.001] # As C decreases, more coefficients go to zero

for c in C:
    clf = LogisticRegression(penalty='l1', C=c, solver='liblinear', class_weight="balanced")
    # using data before splitting (X_scaled) and (y)
    scores = cross_val_score(clf, X_scaled, y, cv=5, scoring="f1_micro")  #<-- add this
    print(scores)  #<-- add this
</code>```

The variable scores now is a list of five values representing the f1_micro value for your classifier over five different splits of your original data.

If you want to use another scoring metric in the sklearn.model_selection.cross_val_score, you can use the following command to get all available scoring metrics:

```<code>print(metrics.SCORERS.keys())
</code>```

Also, you can use multiple scoring metrics; the following uses both f1_micro and f1_macro:

```<code>from sklearn.model_selection import cross_validate

cross_validate(clf, X_scaled, y, cv=5, scoring=["f1_micro", "f1_macro"])
</code>```

Body:
For my logistic regression model, I would like to evaluate the optimal L1 regularization strength using cross validation (eg: 5-fold) in place of a single test-train set as shown below in my code:

from sklearn.model_selection import train_test_split
train_x, test_x, train_y, test_y = train_test_split(X_scaled,y, stratify=y, test_size=0.3,
   random_state=2)

#Evaluate L1 regularization strengths for reducing features in final model
C = [10, 1, .1, 0.05,.01,.001] # As C decreases, more coefficients go to zero

for c in C:
    clf = LogisticRegression(penalty='l1', C=c, solver='liblinear', class_weight="balanced")
    clf.fit(train_x, train_y)
    pred_y=clf.predict(test_x)
    print("Model performance with Inverse Regularization Parameteter, C = 1/λ VALUE: ", c)
    cr=metrics.classification_report(test_y, pred_y)
    print(cr)
    print('')

Can somebody show me how to do this over 5-distinct test-train sets using cross-validation (i.e., without replicating the above code 5-times and distinct random states)?

Body:
Actually, classification_report as a metric is not defined as a scoring metric inside sklearn.model_selection.cross_val_score. So, I will use f1_micro instead in the following code:

from sklearn.model_selection import cross_val_score

#Evaluate L1 regularization strengths for reducing features in final model
C = [10, 1, .1, 0.05,.01,.001] # As C decreases, more coefficients go to zero

for c in C:
    clf = LogisticRegression(penalty='l1', C=c, solver='liblinear', class_weight="balanced")
    # using data before splitting (X_scaled) and (y)
    scores = cross_val_score(clf, X_scaled, y, cv=5, scoring="f1_micro")  #<-- add this
    print(scores)  #<-- add this

The variable scores now is a list of five values representing the f1_micro value for your classifier over five different splits of your original data.

If you want to use another scoring metric in the sklearn.model_selection.cross_val_score, you can use the following command to get all available scoring metrics:

print(metrics.SCORERS.keys())

Also, you can use multiple scoring metrics; the following uses both f1_micro and f1_macro:

from sklearn.model_selection import cross_validate

cross_validate(clf, X_scaled, y, cv=5, scoring=["f1_micro", "f1_macro"])


问:
Pyspark dataframe apply function to a row and add row to bottom of dataframe
I have a df that only has one row.

```<code>id   |id2  |score|score2|
----------------------
0    |1    |4    |2     |
</code>```

and i want to add a row of the percent of these to the bottom, i.e. every number divided by 7

```<code>0/7  |1/7  |4/7  |2/7   |

</code>```

but the solution I came up with is incredibly slow

```<code>temp = [i/7 for i in df.collect()[0]]
row = sc.parallelize(Row(temp)).toDF()
df.union(row)

</code>```

This took 21 seconds to run, almost all of which is the last two lines of code.  Is there a better way to do this?  My other thought was to transpose the table then this can easily be done with df.withColumn().  Ideally, I also want to filter out the column with 0, but I haven't really looked into that yet

Body:
I have a df that only has one row.

id   |id2  |score|score2|
----------------------
0    |1    |4    |2     |

and i want to add a row of the percent of these to the bottom, i.e. every number divided by 7

0/7  |1/7  |4/7  |2/7   |

but the solution I came up with is incredibly slow

temp = [i/7 for i in df.collect()[0]]
row = sc.parallelize(Row(temp)).toDF()
df.union(row)

This took 21 seconds to run, almost all of which is the last two lines of code.  Is there a better way to do this?  My other thought was to transpose the table then this can easily be done with df.withColumn().  Ideally, I also want to filter out the column with 0, but I haven't really looked into that yet

Body:
check this out and let me know if it helps

 from pyspark.sql import SparkSession
 from pyspark.sql import functions as F

 spark = SparkSession.builder \
.appName('practice')\
.getOrCreate()

 sc= spark.sparkContext

 df = sc.parallelize([
(0,1,4,2)]).toDF(["id", "id2","score","score2"])

df2 = df.select(*[(F.col(column)/7).alias(column) for column in df.columns])

df3 = df.union(df2)

df3.show()
+---+-------------------+------------------+------------------+
| id|                id2|             score|            score2|
+---+-------------------+------------------+------------------+
|0.0|                1.0|               4.0|               2.0|
|0.0|0.14285714285714285|0.5714285714285714|0.2857142857142857|
+---+-------------------+------------------+------------------+

If you want to. filter out the column having 0 you can use below code

non_zero_cols  = [c for c in df.columns if df[[c]].first()[c] > 0]

df1 = df.select(*non_zero_cols)

df2 = df1.select(*[(F.col(column)/7).alias(column) for column in
df1.columns])

df3 = df1.union(df2)

df3.show()

+-------------------+------------------+------------------+
|                id2|             score|            score2|
+-------------------+------------------+------------------+
|                1.0|               4.0|               2.0|
|0.14285714285714285|0.5714285714285714|0.2857142857142857|
+-------------------+------------------+------------------+

Please check the below code for  df having type column

non_zero_cols  = [c for c in df.columns if df[[c]].first()[c] > 0]

df1 = df.select(*non_zero_cols, F.lit('count').alias('type') )

df2 = df1.select(*[(F.col(column)/7).alias(column) for column in
df1.columns if not column=='type'], F.lit('percent').alias('type'))

df3 = df1.union(df2)

df3.show()

+-------------------+------------------+------------------+-------+
|                id2|             score|            score2|   type|
+-------------------+------------------+------------------+-------+
|                1.0|               4.0|               2.0|  count|
|0.14285714285714285|0.5714285714285714|0.2857142857142857|percent|
+-------------------+------------------+------------------+-------+


问:
How to set min-font-size in CSS
I want to set a minimum font size to every element in my HTML page.

For example if there are elements with font-size less then 12px, then they will change to 12px.

But if there are elements with font-size grater then 12px, they will not change.

Is there any way to do it with CSS?

答:
It will work perfectly with 50px. Which will act as a static and thus as min-width.

font-size: calc(50px + 5vw);
```

Title: How to set min-font-size in CSS


问:
"Disabling" an HTML table with Javascript
I've seen this done in a lot of sites recently, but can't seem to track one down.  Essentially I want to "disable" an entire panel (that's in the form on an HTML table) when a button is clicked.

By disable I mean I don't want the form elements within the table to be usable and I want the table to sort of fade out.

I've been able to accomplish this by putting a "veil" over the table with an absolutely positioned div that has a white background with a low opacity (so you can see the table behind it, but can't click anything because the div is in front of it).  This also adds the faded effect that I want.  However, when I set the height of the veil to 100% it only goes to the size of my screen (not including the scrolling), so if a user scrolls up or down, they see the edge of the veil and that's not pretty.

I'm assuming this is typically done in a different fashion.  Does anyone have some suggestions as a better way to accomplish this?

答:
Another way to do it would be using the opacity property.</p>

```<code>function disablePanel(id) {
   var panel = document.getElementById(id);
   var inputs = panel.querySelectorAll('input, button'); //anything else can go in here
   for (var i=0; i<inputs.length; i++) {
      inputs[i].disabled = true;
   }

   panel.style.opacity = 0.3; //or any other value
}
</code>```

Body:
Another way to do it would be using the opacity property.

function disablePanel(id) {
   var panel = document.getElementById(id);
   var inputs = panel.querySelectorAll('input, button'); //anything else can go in here
   for (var i=0; i<inputs.length; i++) {
      inputs[i].disabled = true;
   }

   panel.style.opacity = 0.3; //or any other value
}


问:
Problem with adding function in crud question
I have one problem with my web application. I wanted to add adding new record function to my entity.
It works but only when record is blank. For example i have 3 records and want to add new one by this function but it want to place it on 1 place then i try one more time and it want to place it on 2 place.

This is my entity, it extend AbstractPersistable class to give new id when i want to add new record it works very well when I'm adding records from data.sql file but not when i insert the code in browser:

```<code>package com.webservice.model;

import javax.persistence.Entity;

import org.springframework.data.jpa.domain.AbstractPersistable;

@Entity
public class User extends AbstractPersistable<Long>{

    private String userId;
    private String userName;
    private String password;

    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

}
</code>```

To add new record i use function called addUser:

```<code>    package com.webservice.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webservice.model.User;
import com.webservice.repository.UserRepository;
import com.webservice.service.UserService;

@Service
public class UserServiceImpl implements UserService{

    private UserRepository userRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public List<User> userList() {
        return userRepository.findAll();
    }

    @Override
    public Optional<User> findOne(Long id) {
        return userRepository.findById(id);
    }

    @Override
    public User addUser(User user) {
        return userRepository.save(user);
    }

    @Override
    public String deleteUser(Long id) {
        userRepository.deleteById(id);
        return "User deleted successfully";
    }

}

</code>```

Return function is injected from this interface:

```<code>package com.webservice.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.webservice.model.User;

public interface UserRepository extends JpaRepository<User, Long>{

}
</code>```

And is implemented in controller package here:

```<code>package com.webservice.controller;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.webservice.model.User;
import com.webservice.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {

    private UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/list")
    public List<User> userList(){
        return userService.userList();

    }

    @RequestMapping("list/add")
    public User addUser(@RequestBody User user) {
        return userService.addUser(user);
    }

    @RequestMapping("/delete/{id}")
    public String deleteUser(@PathVariable Long id) {
        return userService.deleteUser(id);
    }

    @RequestMapping("/list/{id}")
    public Optional<User> findOne(@PathVariable Long id) {
        return userService.findOne(id);
    }

}

</code>```

In rest client i put this code:

```<code>{
  "userId": "id1",
  "userName": "user1",
  "password": "user1"
}
</code>```

To this url: http://localhost:9090/springboot/user/list/add

And program sands me that message(it was 8 time of posting):

```  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.0.RELEASE)

2020-06-02 18:50:00.006  INFO 17908 --- [  restartedMain] com.webservice.Application               : Starting Application on DESKTOP-7IMDU22 with PID 17908 (C:\Users\Daniel\eclipse-workspace\MyWebService\target\classes started by Daniel in C:\Users\Daniel\eclipse-workspace\MyWebService)
2020-06-02 18:50:00.007  INFO 17908 --- [  restartedMain] com.webservice.Application               : No active profile set, falling back to default profiles: default
2020-06-02 18:50:00.486  INFO 17908 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-06-02 18:50:00.501  INFO 17908 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 15ms. Found 1 JPA repository interfaces.
2020-06-02 18:50:00.636  INFO 17908 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 9090 (http)
2020-06-02 18:50:00.637  INFO 17908 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-06-02 18:50:00.638  INFO 17908 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.35]
2020-06-02 18:50:00.671  INFO 17908 --- [  restartedMain] o.a.c.c.C.[.[localhost].[/springboot]    : Initializing Spring embedded WebApplicationContext
2020-06-02 18:50:00.671  INFO 17908 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 660 ms
2020-06-02 18:50:00.755  INFO 17908 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-06-02 18:50:00.762  INFO 17908 --- [         task-1] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-06-02 18:50:00.771  INFO 17908 --- [         task-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Starting...
2020-06-02 18:50:00.776  INFO 17908 --- [         task-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Start completed.
2020-06-02 18:50:00.776  INFO 17908 --- [         task-1] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2020-06-02 18:50:00.790  WARN 17908 --- [  restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-06-02 18:50:00.832  INFO 17908 --- [         task-1] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-06-02 18:50:00.833  INFO 17908 --- [         task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-06-02 18:50:00.915  INFO 17908 --- [         task-2] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2020-06-02 18:50:01.049  INFO 17908 --- [  restartedMain] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
2020-06-02 18:50:01.071  INFO 17908 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 9090 (http) with context path '/springboot'
2020-06-02 18:50:01.072  INFO 17908 --- [  restartedMain] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-06-02 18:50:01.088  INFO 17908 --- [  restartedMain] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-06-02 18:50:01.096  INFO 17908 --- [  restartedMain] com.webservice.Application               : Started Application in 1.125 seconds (JVM running for 43.182)
2020-06-02 18:50:01.100  INFO 17908 --- [  restartedMain] .ConditionEvaluationDeltaLoggingListener : Condition evaluation unchanged
2020-06-02 18:50:04.853  INFO 17908 --- [nio-9090-exec-1] o.a.c.c.C.[.[localhost].[/springboot]    : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-06-02 18:50:04.854  INFO 17908 --- [nio-9090-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-06-02 18:50:04.858  INFO 17908 --- [nio-9090-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 4 ms
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into user (password, user_id, user_name, id) values (?, ?, ?, ?)
2020-06-02 18:52:09.741  WARN 17908 --- [nio-9090-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1062, SQLState: 23000
2020-06-02 18:52:09.742 ERROR 17908 --- [nio-9090-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : Duplicate entry '8' for key 'PRIMARY'
2020-06-02 18:52:09.807 ERROR 17908 --- [nio-9090-exec-6] o.a.c.c.C.[.[.[.[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context with path [/springboot] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '8' for key 'PRIMARY'
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1347) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.5.jar:na]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3235) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3760) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:107) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[na:na]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1352) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:443) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3202) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2370) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:534) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:631) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:385) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178) ~[spring-data-jpa-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at com.sun.proxy.$Proxy111.save(Unknown Source) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:205) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at com.sun.proxy.$Proxy108.save(Unknown Source) ~[na:na]
    at com.webservice.service.impl.UserServiceImpl.addUser(UserServiceImpl.java:35) ~[classes/:na]
    at com.webservice.controller.UserController.addUser(UserController.java:34) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:93) ~[spring-boot-actuator-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) [na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) [na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at java.base/java.lang.Thread.run(Thread.java:844) [na:na]
```

The table has 24 records, when i deleted 4th record when it was 4th round of posting it worked but why it isn't searhing for first empty record.

答:
Please try adding the below and see if that works,</p>

```<code>@Entity
public class User {
        @Id
        @GeneratedValue(
            strategy= GenerationType.AUTO,
            generator="native"
        )
        @GenericGenerator(
            name = "native",
            strategy = "native"
        )
        private Long id;

    ...
    }
</code>```

Body:
I have one problem with my web application. I wanted to add adding new record function to my entity.
It works but only when record is blank. For example i have 3 records and want to add new one by this function but it want to place it on 1 place then i try one more time and it want to place it on 2 place.

This is my entity, it extend AbstractPersistable class to give new id when i want to add new record it works very well when I'm adding records from data.sql file but not when i insert the code in browser:

package com.webservice.model;

import javax.persistence.Entity;

import org.springframework.data.jpa.domain.AbstractPersistable;

@Entity
public class User extends AbstractPersistable<Long>{

    private String userId;
    private String userName;
    private String password;

    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }

}

To add new record i use function called addUser:

    package com.webservice.service.impl;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webservice.model.User;
import com.webservice.repository.UserRepository;
import com.webservice.service.UserService;

@Service
public class UserServiceImpl implements UserService{

    private UserRepository userRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public List<User> userList() {
        return userRepository.findAll();
    }

    @Override
    public Optional<User> findOne(Long id) {
        return userRepository.findById(id);
    }

    @Override
    public User addUser(User user) {
        return userRepository.save(user);
    }

    @Override
    public String deleteUser(Long id) {
        userRepository.deleteById(id);
        return "User deleted successfully";
    }

}

Return function is injected from this interface:

package com.webservice.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import com.webservice.model.User;

public interface UserRepository extends JpaRepository<User, Long>{

}

And is implemented in controller package here:

package com.webservice.controller;

import java.util.List;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.webservice.model.User;
import com.webservice.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {

    private UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/list")
    public List<User> userList(){
        return userService.userList();

    }

    @RequestMapping("list/add")
    public User addUser(@RequestBody User user) {
        return userService.addUser(user);
    }

    @RequestMapping("/delete/{id}")
    public String deleteUser(@PathVariable Long id) {
        return userService.deleteUser(id);
    }

    @RequestMapping("/list/{id}")
    public Optional<User> findOne(@PathVariable Long id) {
        return userService.findOne(id);
    }

}

In rest client i put this code:

{
  "userId": "id1",
  "userName": "user1",
  "password": "user1"
}

To this url: http://localhost:9090/springboot/user/list/add

And program sands me that message(it was 8 time of posting):

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.0.RELEASE)

2020-06-02 18:50:00.006  INFO 17908 --- [  restartedMain] com.webservice.Application               : Starting Application on DESKTOP-7IMDU22 with PID 17908 (C:\Users\Daniel\eclipse-workspace\MyWebService\target\classes started by Daniel in C:\Users\Daniel\eclipse-workspace\MyWebService)
2020-06-02 18:50:00.007  INFO 17908 --- [  restartedMain] com.webservice.Application               : No active profile set, falling back to default profiles: default
2020-06-02 18:50:00.486  INFO 17908 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-06-02 18:50:00.501  INFO 17908 --- [  restartedMain] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 15ms. Found 1 JPA repository interfaces.
2020-06-02 18:50:00.636  INFO 17908 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 9090 (http)
2020-06-02 18:50:00.637  INFO 17908 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-06-02 18:50:00.638  INFO 17908 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.35]
2020-06-02 18:50:00.671  INFO 17908 --- [  restartedMain] o.a.c.c.C.[.[localhost].[/springboot]    : Initializing Spring embedded WebApplicationContext
2020-06-02 18:50:00.671  INFO 17908 --- [  restartedMain] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 660 ms
2020-06-02 18:50:00.755  INFO 17908 --- [  restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-06-02 18:50:00.762  INFO 17908 --- [         task-1] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [name: default]
2020-06-02 18:50:00.771  INFO 17908 --- [         task-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Starting...
2020-06-02 18:50:00.776  INFO 17908 --- [         task-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-2 - Start completed.
2020-06-02 18:50:00.776  INFO 17908 --- [         task-1] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2020-06-02 18:50:00.790  WARN 17908 --- [  restartedMain] JpaBaseConfiguration$JpaWebConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2020-06-02 18:50:00.832  INFO 17908 --- [         task-1] o.h.e.t.j.p.i.JtaPlatformInitiator       : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
2020-06-02 18:50:00.833  INFO 17908 --- [         task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-06-02 18:50:00.915  INFO 17908 --- [         task-2] o.s.b.d.a.OptionalLiveReloadServer       : LiveReload server is running on port 35729
2020-06-02 18:50:01.049  INFO 17908 --- [  restartedMain] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
2020-06-02 18:50:01.071  INFO 17908 --- [  restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 9090 (http) with context path '/springboot'
2020-06-02 18:50:01.072  INFO 17908 --- [  restartedMain] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-06-02 18:50:01.088  INFO 17908 --- [  restartedMain] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-06-02 18:50:01.096  INFO 17908 --- [  restartedMain] com.webservice.Application               : Started Application in 1.125 seconds (JVM running for 43.182)
2020-06-02 18:50:01.100  INFO 17908 --- [  restartedMain] .ConditionEvaluationDeltaLoggingListener : Condition evaluation unchanged
2020-06-02 18:50:04.853  INFO 17908 --- [nio-9090-exec-1] o.a.c.c.C.[.[localhost].[/springboot]    : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-06-02 18:50:04.854  INFO 17908 --- [nio-9090-exec-1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-06-02 18:50:04.858  INFO 17908 --- [nio-9090-exec-1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 4 ms
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into user (password, user_id, user_name, id) values (?, ?, ?, ?)
2020-06-02 18:52:09.741  WARN 17908 --- [nio-9090-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1062, SQLState: 23000
2020-06-02 18:52:09.742 ERROR 17908 --- [nio-9090-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper   : Duplicate entry '8' for key 'PRIMARY'
2020-06-02 18:52:09.807 ERROR 17908 --- [nio-9090-exec-6] o.a.c.c.C.[.[.[.[dispatcherServlet]      : Servlet.service() for servlet [dispatcherServlet] in context with path [/springboot] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '8' for key 'PRIMARY'
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1347) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025) ~[mysql-connector-java-8.0.20.jar:8.0.20]
    at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61) ~[HikariCP-3.4.5.jar:na]
    at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java) ~[HikariCP-3.4.5.jar:na]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3235) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3760) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:107) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.engine.spi.ActionQueue.lambda$executeActions$1(ActionQueue.java:478) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at java.base/java.util.LinkedHashMap.forEach(LinkedHashMap.java:684) ~[na:na]
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:475) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:348) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:40) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1352) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:443) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3202) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2370) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:447) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:183) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:40) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:281) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:101) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
    at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:534) ~[spring-orm-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:743) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:711) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:631) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:385) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:118) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ~[spring-tx-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:178) ~[spring-data-jpa-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:95) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at com.sun.proxy.$Proxy111.save(Unknown Source) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:344) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:205) ~[spring-aop-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at com.sun.proxy.$Proxy108.save(Unknown Source) ~[na:na]
    at com.webservice.service.impl.UserServiceImpl.addUser(UserServiceImpl.java:35) ~[classes/:na]
    at com.webservice.controller.UserController.addUser(UserController.java:34) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
    at java.base/java.lang.reflect.Method.invoke(Method.java:564) ~[na:na]
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:879) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:660) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:93) ~[spring-boot-actuator-2.3.0.RELEASE.jar:2.3.0.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.6.RELEASE.jar:5.2.6.RELEASE]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) [na:na]
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) [na:na]
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-embed-core-9.0.35.jar:9.0.35]
    at java.base/java.lang.Thread.run(Thread.java:844) [na:na]

The table has 24 records, when i deleted 4th record when it was 4th round of posting it worked but why it isn't searhing for first empty record.

Body:
Please try adding the below and see if that works,

@Entity
public class User {
        @Id
        @GeneratedValue(
            strategy= GenerationType.AUTO,
            generator="native"
        )
        @GenericGenerator(
            name = "native",
            strategy = "native"
        )
        private Long id;

    ...
    }


问:
How do I signup without login?
I have an admin user in my application and only admin can create and activate users in this application.

When I create a user, devise made a automatic login for this new user. How I can create a user without automatic login?

答:
I'm not quite sure what you want to achieve:

Simply create a user instance, that can then log in

Create a new user and notify them their account has been created (i.e. "invite them")

In the first case, simply create a User instance with the appropriate information (check which fields you need to complete in the console: they depend on you configuration and the "strategies" you use: confirmable, lockable, etc.)

In the second case, you probably want to check out something like this: https://github.com/scambra/devise_invitable

Title: How do I signup without login?