Cant upload photos and store them as blob to mysql - java

I am trying to upload a photo with html and store it as a blob using Spring JPA
this is my ORM class.
#Entity(name = "Option")
#Table(name = "options")
public class Option {
#Id
#GeneratedValue(
strategy = GenerationType.IDENTITY
)
#Column(
name = "id",
unique = true,
updatable = false
)
private Long id;
#Column(
name = "img_name",
nullable = false,
columnDefinition = "TEXT"
)
private String imgName;
#Column(
name = "img_description",
nullable = false,
columnDefinition = "TEXT"
)
private String imgDesc;
#Lob()
#Column(
name="img_src",
columnDefinition = "bytea"
)
private byte[] imgSrc;
public Option(String imgName, String imgDesc) {
this.imgName=imgName;
this.imgDesc=imgDesc;
}
public Option() {
}
public byte[] getImgSrc() {
return imgSrc;
}
public void setImgSrc(byte[] imgDesc_i) {
this.imgSrc = imgDesc_i;
}
public String getImgName() {
return imgName;
}
public void setImgName(String imgName) {
this.imgName = imgName;
}
public String getImgDesc() {
return imgDesc;
}
public void setImgDesc(String imgDesc) {
this.imgDesc = imgDesc;
}
#Override
public String toString() {
return "Option{" +
"id=" + id +
", imgName='" + imgName + '\'' +
", imgDesc='" + imgDesc + '\'' +
'}';
}
public Option(Long id, String imgName, String imgDesc) {
this.id = id;
this.imgName = imgName;
this.imgDesc = imgDesc;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
and here is my form
<form action="#" th:action="#{/add}" th:object="${option}" method="post">
<div class="modal-body">
<div class="form-group">
<input type="hidden" th:field="*{id}" class="form-control" required>
</div>
<div class="form-group">
<label>Description</label>
<input type="text" th:field="*{imgDesc}" class="form-control" required>
</div>
<div class="form-group">
<label>Image name</label>
<input type="text" th:field="*{imgName}" class="form-control" required>
</div>
<div class="form-group">
<label class="form-label" >Upload image</label>
<input th:field="*{imgSrc}" type="file" class="form-control" />
</div>
</div>
<div class="modal-footer">
Cancel
<input type="submit" class="btn btn-success" value="Save">
</div>
</form>
and this is my controller
#PostMapping("/add")
public String addOption(#ModelAttribute("option") Option option) {
optionService.save(option);
return "redirect:/admin";
}
The problem is that I keep img src in Option class as array of bytes.
at MySQL dbms shows that type of imgSrc is blob
so when I am trying to save using jpa repository, it just saves image name.
could someone help me to solve issue?
thank You

Related

Convert String to Money Thymeleaf

I am having a problem converting input String to money. I am creating a spring boot application with thymeleaf. I have a web page where user inputs the data and there is a particular field where he inputs the String and it needs to be converted to type joda.money as in my pojo class that field has money data type. This is a full governor_form.html:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>[[${pageTitleG}]]</title>
<link rel="stylesheet" type="text/css" th:href="#{/webjars/bootstrap/css/bootstrap.min.css}"/>
</head>
<body>
<div class="container-fluid">
<div class="text-center"><h2>[[${pageTitleG}]]</h2></div>
<form th:action="#{/governors/save}" method="post" th:object="${governor}" style="max-width: 550px; margin: 0 auto;">
<input type="hidden" th:field="*{idGovernor}">
<div class="border border-secondary rounded p-3">
<div class="form-group row">
<label class="col-sm-4 col-form-label">Full name:</label>
<div class="col-sm-8">
<input type="text" th:field="*{fullName}" class="form-control" required minlength="5" maxlength="70">
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Age</label>
<div class="col-sm-8">
<input type="number" step="0.01" th:field="*{age}" class="form-control" required>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Position</label>
<div class="col-sm-8">
<input type="text" step="0.01" th:field="*{position}" class="form-control" required>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Date of Intercession</label>
<div class="col-sm-8">
<input type="date" th:field="*{dateOfIntercession}" class="form-control">
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Date of Resignation</label>
<div class="col-sm-8">
<input type="date" th:field="*{dateOfResignation}" class="form-control">
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Per Capita Income</label>
<div class="col-sm-8">
<input type="number" step="0.01" th:field="*{perCapitaIncome}" class="form-control" required>
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">Population Below Poverty</label>
<div class="col-sm-8">
<input type="number" step="0.01" th:field="*{populationBelowPoverty}" class="form-control" required min="0" max="99">
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label">State</label>
<div class="col-sm-8">
<select th:field="*{state}" class="form-control" required>
<th:block th:each="state : ${listStates}">
<option th:text="${state.officialStateName}" th:value="${state.idState}"/>
</th:block>
</select>
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary m-2">Save</button>
<button type="button" class="btn btn-secondary m-2" onclick="cancelForm()">Cancel</button>
</div>
</div>
</form>
</div>
<script type="text/javascript">
function cancelForm() {
window.location = "[[#{/governors}]]";
}
</script>
</body>
</html>
This is where he inputs that data:
<div class="form-group row">
<label class="col-sm-4 col-form-label">Per Capita Income</label>
<div class="col-sm-8">
<input type="number" step="0.01" th:field="*{perCapitaIncome}" class="form-control" required>
</div>
</div>
So if i'm not mistaken Hibernate is having a problem converting a String input from thymeleaf to type money as I get the following error:
: Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors<EOL>Field error in object 'governor' on field 'perCapitaIncome': rejected value [1100]; codes [typeMismatch.governor.perCapitaIncome,typeMismatch.perCapitaIncome,typeMismatch.org.joda.money.Money,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [governor.perCapitaIncome,perCapitaIncome]; arguments []; default message [perCapitaIncome]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'org.joda.money.Money' for property 'perCapitaIncome'; Cannot convert value of type 'java.lang.String' to required type 'org.joda.money.Money' for property 'perCapitaIncome': no matching editors or conversion strategy found]]
This is the joda.money dependency:
<dependency>
<groupId>org.joda</groupId>
<artifactId>joda-money</artifactId>
<version>1.0.1</version>
</dependency>
This is a POJO class:
#Entity
#Table(name = "governor")
public class Governor implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_governor")
private Integer idGovernor;
#Column(name = "pib")
private String fullName;
#Column(name = "age")
private Integer age;
#Column(name = "position")
private String position;
#Column(name = "date_of_intercession")
private java.sql.Date dateOfIntercession;
#Column(name = "date_of_resignation")
private java.sql.Date dateOfResignation;
#Column(name = "per_capita_income")
private Money perCapitaIncome;
#Column(name = "population_below_poverty")
private Integer populationBelowPoverty;
#ManyToOne
#JoinColumn(name = "id_state", nullable = false)
private State state;
public State getState() {return state;}
public void setState(State state) {this.state = state;}
public Integer getIdGovernor() {
return this.idGovernor;
}
public void setIdGovernor(Integer idGovernor) {
this.idGovernor = idGovernor;
}
public String getFullName() {
return this.fullName;
}
public void setFullName(String fullName) {this.fullName = fullName;}
public Integer getAge() {
return this.age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPosition() {
return this.position;
}
public void setPosition(String position) {
this.position = position;
}
public java.sql.Date getDateOfIntercession() {
return this.dateOfIntercession;
}
public void setDateOfIntercession(java.sql.Date dateOfIntercession) {
this.dateOfIntercession = dateOfIntercession;
}
public java.sql.Date getDateOfResignation() {
return this.dateOfResignation;
}
public void setDateOfResignation(java.sql.Date dateOfResignation) {
this.dateOfResignation = dateOfResignation;
}
public Money getPerCapitaIncome() {
return this.perCapitaIncome;
}
public void setPerCapitaIncome(Money perCapitaIncome) {
this.perCapitaIncome = perCapitaIncome;
}
public Integer getPopulationBelowPoverty() {
return this.populationBelowPoverty;
}
public void setPopulationBelowPoverty(Integer populationBelowPoverty) {
this.populationBelowPoverty = populationBelowPoverty;
}
}
This is a controller:
#Controller
public class GovernorController {
#Autowired
GovernorService governorService;
#Autowired
GovernorRepository governorRepository;
#Autowired
StateRepository stateRepository;
#Autowired
StateService stateService;
#GetMapping("/governors")
public String showAllGovernors(Model model){
List<Governor> listGovernors = governorService.findAllGovernors();
model.addAttribute("listGovernors", listGovernors);
return "governors";
}
#GetMapping("/governors/new")
public String showNewGovernorForm(Model model){
List <State> listStates = stateService.findAll();
model.addAttribute("listStates", listStates);
model.addAttribute("governor", new Governor());
model.addAttribute("pageTitleG", "Add New Governor");
return "governor_form";
}
#PostMapping("/governors/save")
public String saveGovernor (Governor requestGovernor, RedirectAttributes redirectAttributes){
governorRepository.save(requestGovernor);
redirectAttributes.addFlashAttribute("messageG", "The governor has been saved successfully!");
return "redirect:/governors";
}
#GetMapping("/governors/edit/{id}")
public String showEditGovernorForm(#PathVariable("id") Integer id, Model model, RedirectAttributes redirectAttributes){
try {
Governor governor = governorService.findGovernorById(id);
List <State> listStates = stateService.findAll();
model.addAttribute("listStates", listStates);
model.addAttribute("governor", governor);
model.addAttribute("pageTitleG", "Edit Governor (ID: " + id + ")");
return "governor_form";
} catch (EntityNotFoundException e) {
redirectAttributes.addFlashAttribute("messageG", e.getMessage());
return "redirect:/governors";
}
}
#GetMapping("/governors/delete/{id}")
public String deleteGovernor(#PathVariable("id") Integer id, Model model, RedirectAttributes redirectAttributes){
try {
governorService.deleteGovernor(id);
redirectAttributes.addFlashAttribute("messageG", "The governor ID " + id + " has been deleted!");
} catch (StateNotFoundException e) {
redirectAttributes.addFlashAttribute("messageG", e.getMessage());
}
return "redirect:/governors";
}
}
How do I convert String to Money?
One solution would be to create custom deserilizer for Money field, and then use Jackson to set it.
Here is code snippet:
MoneyDeserializer.java :
public class MoneyDeserializer extends StdDeserializer<BigMoney> {
private static final long serialVersionUID = 2518470236548239933L;
public MoneyDeserializer() {
super(Money.class);
}
#Override
public BigMoney deserialize(final JsonParser jp, final DeserializationContext ctxt) throws IOException, JsonProcessingException {
return BigMoney.of(CurrencyUnit.USD, jp.readValueAs(Double.class));
}
}
Governor.java
import com.example.demo.filter.MoneyDeserializer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.joda.money.BigMoney;
import org.joda.money.Money;
import java.io.Serializable;
public class Governor implements Serializable {
private Integer idGovernor;
private String fullName;
private Integer age;
private String position;
private java.sql.Date dateOfIntercession;
private java.sql.Date dateOfResignation;
private BigMoney perCapitaIncome;
private Integer populationBelowPoverty;
public Integer getIdGovernor() {
return this.idGovernor;
}
public void setIdGovernor(Integer idGovernor) {
this.idGovernor = idGovernor;
}
public String getFullName() {
return this.fullName;
}
public void setFullName(String fullName) {this.fullName = fullName;}
public Integer getAge() {
return this.age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getPosition() {
return this.position;
}
public void setPosition(String position) {
this.position = position;
}
public java.sql.Date getDateOfIntercession() {
return this.dateOfIntercession;
}
public void setDateOfIntercession(java.sql.Date dateOfIntercession) {
this.dateOfIntercession = dateOfIntercession;
}
public java.sql.Date getDateOfResignation() {
return this.dateOfResignation;
}
public void setDateOfResignation(java.sql.Date dateOfResignation) {
this.dateOfResignation = dateOfResignation;
}
public BigMoney getPerCapitaIncome() {
return this.perCapitaIncome;
}
#JsonDeserialize(using = MoneyDeserializer.class)
public void setPerCapitaIncome(BigMoney perCapitaIncome) {
this.perCapitaIncome = perCapitaIncome;
}
public Integer getPopulationBelowPoverty() {
return this.populationBelowPoverty;
}
public void setPopulationBelowPoverty(Integer populationBelowPoverty) {
this.populationBelowPoverty = populationBelowPoverty;
}
#Override
public String toString() {
return "Governor{" +
"idGovernor=" + idGovernor +
", fullName='" + fullName + '\'' +
", age=" + age +
", position='" + position + '\'' +
", dateOfIntercession=" + dateOfIntercession +
", dateOfResignation=" + dateOfResignation +
", perCapitaIncome=" + perCapitaIncome +
", populationBelowPoverty=" + populationBelowPoverty +
'}';
}
}
NOTE: On your form, you are passing age field as Double, but in your class it's declared as Integer. So you will get exception during deserilization process.
Same thing applys for populationBelowPoverty field . Also, your date format is dd/MM/YYYY and I think this is not supported format for jackson. It should be YYYY-MM-dd.
Anyway, for example, if you send a JSON like this:
{
"idGovernor":1,
"fullName":"Test",
"age":1,
"dateOfIntercession":"2022-06-09",
"dateOfResignation":"2022-06-17",
"perCapitaIncome":"123.932",
"position":"position",
"populationBelowPoverty":"98"
}
to this controller method:
#PostMapping(value = "/test/governor")
public Governor testGovernor(#RequestBody Governor governor) {
return governor;
}
You should get response like this :
{
"idGovernor": 1,
"fullName": "Test",
"age": 1,
"position": "position",
"dateOfIntercession": "2022-06-09",
"dateOfResignation": "2022-06-17",
"perCapitaIncome": {
"amount": 123.932,
"zero": false,
"negative": false,
"positive": true,
"amountMajorLong": 123,
"negativeOrZero": false,
"amountMinorLong": 12393,
"amountMinor": 12393,
"positiveOrZero": true,
"minorPart": 93,
"scale": 3,
"amountMinorInt": 12393,
"currencyUnit": {
"code": "USD",
"numericCode": 840,
"decimalPlaces": 2,
"symbol": "$",
"numeric3Code": "840",
"countryCodes": [
"PR",
"MP",
"IO",
"FM",
"PW",
"GU",
"BQ",
"TC",
"VG",
"AS",
"VI",
"TL",
"UM",
"MH",
"EC",
"US"
],
"pseudoCurrency": false
},
"currencyScale": false,
"amountMajorInt": 123,
"amountMajor": 123
},
"populationBelowPoverty": 98
}
In your case, since you are using thymeleaf you can adjust this idea to your needs.

Send multipartfile jsp spring mvc to controller

I have a JSP project with Spring MVC. And I have a screen with a registration form (CRUD). I put an input file field to attach files. And I'm trying to send the attached file to the Model. But without success. Could someone tell me what is wrong with my implementation?
index.jsp:
<div class="modal fade" id="modalNovoResultado" tabindex="-1" role="dialog"
aria-labelledby="novoResultadoModal" aria-hidden="true">
<div class="modal-dialog" role="document">
<form:form method="POST" id="newResultado" modelAttribute="exameForm" action="criarResultado.do">
<div class="modal-content novo-resultado" style="padding: 0px !important;" >
<div class="modal-line novo-resultado"></div>
<div class="modal-header novo-resultado">
<p class="modal-title novo-resultado" id="exampleModalLabel" style="margin-top:10px;">Novo
resultado de exame</p>
</div>
<div class="modal-body pb-0">
<div class="container">
<div class="row mt-1">
<div class="form-group text-left col-md-6 tipo-exame">
<label class="modal-resultado">
Tipo de exame: <span class="required">*</span>
</label>
<form:select class="selectpicker form-control" id="tipoExameNew" path="tipoExame">
<form:option value="" selected hidden>Selecione</form:option>
<form:option value="999" selected hidden>Antígeno SarsCovid-19</form:option>
</form:select>
</div>
<div class="form-group text-left col-md-6 mb-0">
<label class="modal-resultado">
Anexe de um a três arquivos: <span class="required">*</span>
<img class="anexar-exame"
src="/PCBS-GestaoNovamed/includes/img/icon-nav-anexar.svg" alt=""
data-toggle="modal">
<form:input path="arquivo" id="fileModal" type="file" name="arquivo"/>
</label>
<label class="anexo-subtitle" style="font-size: 12px;">Arquivos PDF, JPG ou PNG, com
no máximo 10mb</label>
</div>
</div>
<div class="row">
<div style="margin-left: 230px;">
<div class="row botoes-formulario" style="float: right;">
<input type="submit" class="add-unidade-button cadastrar" value="Cadastrar"
onclick="validaForm()"/>
</div>
</div>
</div>
</div>
</div>
</div>
</form:form>
</div>
</div>
javascript:
function adicionarExame(element, event) {
event.preventDefault();
if (validaForm() > 0) return;
var form = document.getElementById('newResultado');
console.log("form:" + $(form).serialize());
$.ajax({
method: 'POST',
url: element.action,
data: $(form).serialize(),
cache: false,
success: function (status) {
Swal.fire({
customClass: {
title: 'title-class',
popup: 'popup-class popup-green',
content: 'content-class',
actions: 'actions-class-green'
},
type: 'success',
title: 'Resultado cadastrado com sucesso.',
text: ''
}).then(function () {
//window.location.reload();
})
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(thrownError);
var msgErro = 'Erro inesperado';
if (xhr.status === 400) {
msgErro = 'Erro ao cadastrar resultado.';
}
Swal.fire({
customClass: {
title: 'title-class',
popup: 'popup-class popup-red',
content: 'content-class',
actions: 'actions-class-red'
},
type: '',
title: msgErro,
text: ''
})
}
});
}
controller:
#RequestMapping(value = "criarResultado.do", method = RequestMethod.POST)
public ResponseEntity<ExameVO> cadastrarNovoExame(
#Valid #ModelAttribute(Constants.MA_MODEL_RESULTADO_EXAME) ExameForm exameForm,
BindingResult bindingResult,
Model model) {
LOGGER.error("entrou em criarResultado form" + exameForm.toString());
}
model:
#Component
#Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ExameForm implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
//#NotNull(message = Constants.MSG_ERRO_CAMPO_OBRIGATORIO)
private String cpf;
//#NotNull(message = Constants.MSG_ERRO_CAMPO_OBRIGATORIO)
//#DateTimeFormat(pattern = "dd/MM/yyyy")
private String dataNascimento;
//#NotNull(message = Constants.MSG_ERRO_CAMPO_OBRIGATORIO)
private Long tipoExame;
//#NotNull(message = Constants.MSG_ERRO_CAMPO_OBRIGATORIO)
//private List<ExameArquivoVO> resultadoExameArquivos;
private MultipartFile arquivo;
private String observacao;
private String excluido;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public String getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(String dataNascimento) {
this.dataNascimento = dataNascimento;
}
public Long getTipoExame() {
return tipoExame;
}
public void setTipoExame(Long tipoExame) {
this.tipoExame = tipoExame;
}
public String getObservacao() {
return observacao;
}
public void setObservacao(String observacao) {
this.observacao = observacao;
}
public String getExcluido() {
return excluido;
}
public void setExcluido(String excluido) {
this.excluido = excluido;
}
/*
public List<ExameArquivoVO> getResultadoExameArquivos() {
return resultadoExameArquivos;
}
public void setResultadoExameArquivos(List<ExameArquivoVO> resultadoExameArquivos) {
this.resultadoExameArquivos = resultadoExameArquivos;
}
*/
public MultipartFile getArquivo() {
return arquivo;
}
public void setArquivo(MultipartFile arquivo) {
this.arquivo = arquivo;
}
public ExameVO toVo() {
ExameVO vo = new ExameVO();
vo.setId(this.getId());
vo.setCpf(this.getCpf());
vo.setDataNascimento(this.getDataNascimento());
vo.setTipoExame(this.getTipoExame());
vo.setObservacao(this.getObservacao());
vo.setExcluido(this.getExcluido());
//vo.setResultadoExameArquivos(this.getResultadoExameArquivos());
vo.setFile(this.getArquivo());
return vo;
}
#Override
public String toString() {
return "ExameForm [id=" + id + ", cpf=" + cpf + ", dataNascimento=" + dataNascimento + ", tipoExame="
+ tipoExame + ", arquivo=" + arquivo + ", observacao=" + observacao + ", excluido=" + excluido + "]";
}
}

Why I Can't Do Mapping using Many-To-One

Do anyone knows why I can't do mapping using many-to-one?
This is my model
#Entity(name="trxrawatjalan")
public class Rawatjalan implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int idRawatjalan;
#Column(nullable = false, insertable = false, updatable = false)
private int idPasien;
#Column(nullable = false, insertable = false, updatable = false)
private int idDokter;
#Column(nullable = false, insertable = false, updatable = false)
private int idTreatment;
public Rawatjalan() {
}
public Rawatjalan(int idRawatjalan) {
this.idRawatjalan = idRawatjalan;
}
public int getIdPasien() {
return idPasien;
}
public void setIdPasien(int idPasien) {
this.idPasien = idPasien;
}
public int getIdDokter() {
return idDokter;
}
public void setIdDokter(int idDokter) {
this.idDokter = idDokter;
}
public int getIdTreatment() {
return idTreatment;
}
public void setIdTreatment(int idTreatment) {
this.idTreatment = idTreatment;
}
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name= "idPasien", nullable = false)
private Pasien pasien;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name= "idDokter", nullable = false)
private Dokter dokter;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name= "idTreatment", nullable = false)
private Treatment treatment;
public int getIdRawatjalan() {
return idRawatjalan;
}
public void setIdRawatjalan(int idRawatjalan) {
this.idRawatjalan = idRawatjalan;
}
#Override
public String toString () {
return "Rawatjalan{" +
"idRawatjalan=" + idRawatjalan +
'}';
This is my trxindex.jsp:
<c:forEach var="rawatjalan" items="${rawatjalans}">
<tr>
<td>${rawatjalan.idRawatjalan}</td>
<td>${rawatjalan.pasien.idPasien}</td>
<td>${rawatjalan.dokter.idDokter}</td>
<td>${rawatjalan.treatment.idTreatment}</td>
<td><span class="glyphicon glyphicon-pencil"></span></td>
<td><span class="glyphicon glyphicon-trash"></span></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
<form class="form-horizontal" method="POST" action="save-treatment">
<input type="hidden" name="idRawatjalan" value="${rawatjalan.idRawatjalan}"/>
<div class="form-group">
<label class="control-label col-md-3">Id Pasien</label>
<div class="col-md-7">
<input type="text" class="form-control" name="rawatjalan.pasien.idPasien" value="${rawatjalan.pasien.idPasien}"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">id Dokter</label>
<div class="col-md-7">
<input type="text" class="form-control" name="rawatjalan.dokter.idDokter" value="${rawatjalan.dokter.idDokter}"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">id Treatment</label>
<div class="col-md-7">
<input type="text" class="form-control" rows="3" name="rawatjalan.treatment.idTreatment" value="${rawatjalan.treatment.idTreatment}"/>
</div>
</div>
This is my controller:
#Autowired
private TrxService trxService;
#GetMapping("/data-rawatjalan")
public String dataRawatjalans(HttpServletRequest request){
request.setAttribute("rawatjalans", trxService.findAll());
request.setAttribute("mode", "MODE_TASKS");
return "indextrx";
}
#GetMapping("/new-rawatjalan")
public String newRawatjalan(HttpServletRequest request){
request.setAttribute("mode", "MODE_NEW");
return "indextrx";
}
#PostMapping("/save-rawatjalan")
public String saveRawatjalan(#ModelAttribute Rawatjalan rawatjalan, BindingResult bindingResult, HttpServletRequest request){
trxService.save(rawatjalan);
request.setAttribute("rawatjalans", trxService.findAll());
request.setAttribute("mode", "MODE_TASKS");
return "indextrx";
}
#GetMapping("/update-rawatjalan")
public String updateRawatjalan(#RequestParam int idRawatjalan, HttpServletRequest request){
request.setAttribute("rawatjalan", trxService.findRawatjalan(idRawatjalan));
request.setAttribute("mode", "MODE_UPDATE");
return "indextrx";
}
#GetMapping("/delete-rawatjalan")
public String deleteRawatjalan(#RequestParam int idRawatjalan, HttpServletRequest request){
trxService.delete(idRawatjalan);
request.setAttribute("rawatjalans", trxService.findAll());
request.setAttribute("mode", "MODE_TASKS");
return "indextrx";
}
This is my service:
#Service
#Transactional
public class TrxService {
private final TrxinapRepository trxinapRepository;
public TrxService(TrxinapRepository trxinapRepository) {
this.trxinapRepository = trxinapRepository;
}
public List<Rawatjalan> findAll(){
List<Rawatjalan> rawatjalans = new ArrayList<>();
for(Rawatjalan rawatjalan : trxinapRepository.findAll()){
rawatjalans.add(rawatjalan);
}
return rawatjalans;
}
public Rawatjalan findRawatjalan(int idRawatjalan){
return trxinapRepository.findOne(idRawatjalan);
}
public void save(Rawatjalan rawatjalan){
trxinapRepository.save(rawatjalan);
}
public void delete(int idRawatjalan){
trxinapRepository.delete(idRawatjalan);
}
}
My Repository
package bootsample.dao;
import bootsample.mod`enter code here`el.Rawatjalan;
import org.springframework.data.repository.CrudRepository;
public interface TrxinapRepository extends CrudRepository<Rawatjalan, Integer>{
}
2019-05-19 03:10:50.977 ERROR 1712 --- [nio-8030-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [An exception occurred processing JSP page /WEB-INF/jsp/indextrx.jsp at line 77
74:
75:
76: ${rawatjalan.idRawatjalan}
77: ${rawatjalan.pasien.idPasien}
78: ${rawatjalan.dokter.idDokter}
79: ${rawatjalan.treatment.idTreatment}
80:
Stacktrace:] with root cause
javax.el.PropertyNotFoundException: Property 'pasien' not found on type bootsample.model.Rawatjalan

Adding image to mysql database doesn't work

Hi i want to add my photo to mysql database but it doesn't work, I have BLOB in workbench but when I open value in editor I see only name of image and binary values, I don't have look at the picture and size of BLOB do not agree with size of image. Text entites correctly save to rows.
MODEL:
#Entity
#Table(name = "skis")
public class Skis extends BaseEntity {
#Column(name = "company", length = 20)
private String company;
#Column(name = "model", length = 20)
private String model;
#Column(name = "description", length = 200)
private String description;
#Column(name = "photo", columnDefinition = "MEDIUMBLOB")
private byte[] photo;
public Skis(String company, String model, String description, byte[] photo) {
this.company = company;
this.model = model;
this.description = description;
this.photo = photo;
}
public Skis() {
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
}
Controller:
#Controller
public class SkisController {
#Autowired
private SkisDAO skisDAO;
#RequestMapping(value = "/ski/save", method = RequestMethod.POST)
public String postCreateSki(#ModelAttribute Skis skis){
skisDAO.save(skis);
return "redirect:/skis";
}
#RequestMapping(value = "/ski-create", method = RequestMethod.GET)
public String getCreateSkisForm(Model model) {
model.addAttribute("skis", new Skis());
return "add-skis";
}
}
JSP:
<div class="container">
<div class="row">
<form:form commandName="skis" action="${createSkiURL}" method="post" role="form" class="form-horizontal">
<form:hidden path="id" />
<div class="form-group">
<label class="control-label col-sm-2" for="company">company:</label>
<div class="col-sm-6">
<form:input path="company" type="text" id="company" class="form-control" placeholder="Enter company" autofocus="autofocus" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="model">model:</label>
<div class="col-sm-6">
<form:input path="model" type="text" id="model" class="form-control" placeholder="Enter model" autofocus="autofocus" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="description">description:</label>
<div class="col-sm-6">
<form:input path="description" type="text" id="description" class="form-control" placeholder="Enter description" autofocus="autofocus" />
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="photo">photo:</label>
<form:input path="photo" type="file" id="photo" />
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-6">
<button type="submit" class="btn btn-primary">Zapisz</button>
</div>
</div>
</form:form>
</div>
</div>
DAO:
#Repository
public interface SkisDAO extends JpaRepository<Skis, Long> {
}
And another question:
How Can I display image at another jsp? I know how display text, but don't know how to display photo from database

Validation failed for object='auctionItem'

When trying to submit my form to create a new auction this error appears in the browser:
Whitelabel Error Page:
This application has no explicit mapping for /error, so you are seeing
this as a fallback.
Thu Mar 30 21:00:15 BST 2017
There was an unexpected error (type=Bad Request, status=400)
Validation failed for object='auctionItem'. Error count: 2
I can't seem to find any specific errors within my log, so I am having trouble finding the two validation errors show on the error page. I am pretty lost at this point. Hopefully someone can help me out, its preventing me from making progress at the moment.
JSP File:
<body id="product" class="product">
<header>
<%#include file="../jsp/Header.jsp" %>
</header>
<div>
<div class="container">
<div class ="row">
<div class="center_column">
<h2 style=" ">Create New Listing</h2>
<mvc:form class="form-inline" action="sell" method="post" modelAttribute="newAuction" id="addNewAuc">
<div class="form-inline" cssClass="TitleBlock">
<label class="control-label">Title</label>
<div>
<mvc:input path="aTitle" type="text" required="true" cssClass="Title" class="form-control" placeholder="Please enter title of item" maxlength="55" minlength="40"/>
</div>
</div>
<div class="form-group ">
<label class="control-label">Item Condition</label>
<div style="padding-top: 4px;">
<mvc:select path="aCondition">
<mvc:option value="New">New</mvc:option>
<mvc:option value="Used">Used</mvc:option>
</mvc:select>
</div>
</div>
<div class="form-group ">
<label class="control-label" style = "padding-left: 15px;">Can the item be returned?</label>
<div style="padding-top: 4px; padding-left: 15px;">
<mvc:select path="aReturns">
<mvc:option value="You can return">Yes</mvc:option>
<mvc:option value="Seller does not offer returns">No</mvc:option>
</mvc:select>
</div>
</div>
<div class="form-inline">
<label class="control-label">Description</label>
<div>
<mvc:textarea path="aDescription" required="true" cssClass="Desc" class="form-control" rows="3" name="Description" placeholder="Item description"/>
</div>
</div>
<div class="form-inline">
<label class="control-label">Category</label>
<div style="padding-top: 4px;">
<mvc:select path="categories">
<mvc:option value="category1">Electronics</mvc:option>
<mvc:option value="category2">Fashion</mvc:option>
<mvc:option value="category3">Home & Gardens</mvc:option>
<mvc:option value="category4">Toys & Games</mvc:option>
<mvc:option value="category5">Sports & Leisure</mvc:option>
</mvc:select>
</div>
</div>
<div class="form-inline">
<label class="control-label ">Minimum Price</label>
<div style="padding-top: 4px;">
<mvc:input path="aBottomPrice" type="number" step="any" required="true" class="form-control" placeholder="?"/>
</div>
</div>
<div class="form-inline">
<label class="control-label ">Starting Price</label>
<div style="padding-top: 4px;">
<mvc:input path="aTopPrice" type="number" step="any" required="true" class="form-control" placeholder="?"/>
</div>
</div>
<div class="form-inline">
<label class="control-label">End of listing</label>
<div style="padding-top: 4px;">
<mvc:input path="aEnd" type="text" id="datetimepicker" required="true" class="form-control" placeholder="YYYY-MM-DD"/>
</div>
</div>
</mvc:form>
<div class="form-inline">
<div style="padding-top: 10px;">
<button type="submit" name="submit" class="btn btn-success" form="addNewAuc">Next</button>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
AuctionItem Class
#Entity
#Table(name = "auction_items")
public class AuctionItem {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idauction;
#Column(name = "auctionTitle")
private String aTitle;
#Column(name = "auctionDescription")
private String aDescription;
#Column(name = "auctionStatus")
private String aStatus;
#Column(name = "auctionStart")
private Date aStart;
#Column(name = "auctionEnd")
private Date aEnd;
private String endTimeAsString;
#Column(name = "auctionCondition")
private String aCondition;
#Column(name = "auctionTopPrice")
private double aTopPrice;
#Column(name = "auctionBottomPrice")
private double aBottomPrice;
private long auctionDuration;
private String aReturns;
#ManyToOne
#JoinColumn(name = "owner")
private User owner;
#ManyToOne
#JoinColumn(name = "cId")
private Category categories;
public long getAuctionDuration() {
return auctionDuration;
}
public void setAuctionDuration(long auctionDuration) {
this.auctionDuration = auctionDuration;
}
public int getaID() {
return idauction;
}
public void setaID(int idauction) {
this.idauction = idauction;
}
public String getaTitle() {
return aTitle;
}
public void setaTitle(String aTitle) {
this.aTitle = aTitle;
}
public String getaDescription() {
return aDescription;
}
public void setaDescription(String aDescription) {
this.aDescription = aDescription;
}
public String getaStatus() {
return aStatus;
}
public void setaStatus(String aStatus) {
this.aStatus = aStatus;
}
public Date getaStart() {
return aStart;
}
public void setaStart(Date aStart) {
this.aStart = aStart;
}
public Date getaEnd() {
return aEnd;
}
public void setaEnd(Date aEnd) {
this.aEnd = aEnd;
}
public String getaCondition() {
return aCondition;
}
public void setaCondition(String aCondition) {
this.aCondition = aCondition;
}
public double getaTopPrice() {
return aTopPrice;
}
public void setaTopPrice(double aTopPrice) {
this.aTopPrice = aTopPrice;
}
public double getaBottomPrice() {
return aBottomPrice;
}
public void setaBottomPrice(double aBottomPrice) {
this.aBottomPrice = aBottomPrice;
}
public User getOwner() {
return owner;
}
public void setOwner(User owner) {
this.owner = owner;
}
public String getaReturns() {
return aReturns;
}
public void setaReturns(String aReturns) {
this.aReturns = aReturns;
}
public Category getCategories() {
return categories;
}
public void setCategories(Category categories) {
this.categories = categories;
}
public String getEndTimeAsString() {
return endTimeAsString;
}
public void setEndTimeAsString(String EndTimeAsString) {
this.endTimeAsString = EndTimeAsString;
}
}
Maybe you missed " BindingResult " in Controller.
Example:
import org.springframework.validation.BindingResult;
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(
#ModelAttribute("userlogin") #Valid LoginProfile userlogin,
BindingResult userloginResult)

Categories